<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>人员管理系统 - 管理面板</title>
    <style>
        /* 重置样式 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: "HarmonyOS Sans SC", "Microsoft YaHei", sans-serif;
            height: 100vh;
            display: flex;
            flex-direction: column;
        }

        /* 顶部导航 */
        .header {
            background-color: #1c2b36;
            padding: 20px 0;
            height: 18vh;
            min-height: 18vh;
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 0 20px;
        }

        .header h1 {
            color: white;
            font-size: 24px;
            font-weight: normal;
        }

        /* 用户信息 */
        .user-info {
            display: flex;
            align-items: center;
            gap: 20px;
            color: white;
        }

        .user-info .username {
            font-weight: bold;
        }

        .user-info .role {
            background-color: rgba(255, 255, 255, 0.1);
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 14px;
        }

        .logout-btn {
            padding: 6px 12px;
            background-color: rgba(255, 255, 255, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.2);
            color: white;
            border-radius: 4px;
            cursor: pointer;
            text-decoration: none;
            transition: all 0.2s;
        }

        .logout-btn:hover {
            background-color: rgba(255, 255, 255, 0.2);
        }

        /* 主内容区域 - 82% */
        .main-container {
            height: 82vh;
            display: flex;
        }

        /* 左侧导航 - 20% */
        .sidebar {
            width: 20%;
            background-color: #f8f9fa;
            border-right: 1px solid #e9ecef;
            padding: 20px;
            overflow-y: auto;
        }

        /* 右侧内容 - 80% */
        .content {
            width: 80%;
            padding: 20px;
            overflow-y: auto;
            background-color: white;
        }

        /* 导航菜单样式 */
        .nav-submenu {
            margin-left: 20px;
            display: none;
            transition: all 0.3s ease;
        }

        .nav-submenu.show {
            display: block;
        }

        .nav-submenu .nav-item {
            padding: 8px 15px;
            font-size: 14px;
            color: #666;
        }

        .nav-item.has-submenu {
            position: relative;
        }

        .nav-item.has-submenu:after {
            content: "";
        }

        /* 导航项样式 */
        .nav-item {
            padding: 10px;
            margin-bottom: 8px;
            background-color: #e9ecef;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.2s;
        }

        .nav-item:hover {
            background-color: #dee2e6;
        }

        .nav-item.active {
            background-color: #1c2b36;
            color: white;
        }

        /* 内容区域样式 */
        .content-section {
            padding: 30px;
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
        }

        .content-section h2 {
            color: #1c2b36;
            font-size: 24px;
            font-weight: normal;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid #e9ecef;
        }

        /* 表格样式 */
        .table-container {
            margin-top: 20px;
            overflow-x: auto;
        }

        .data-table {
            width: 100%;
            border-collapse: collapse;
            background: white;
        }

        .data-table th,
        .data-table td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #e9ecef;
        }

        .data-table th {
            background: #f8f9fa;
            color: #1c2b36;
            font-weight: normal;
        }

        .data-table tr:hover {
            background-color: #f8f9fa;
        }

        /* 按钮样式 */
        .btn {
            padding: 8px 16px;
            background-color: #1c2b36;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.2s;
            font-size: 14px;
        }

        .btn:hover {
            background-color: #2d3e4a;
        }

        .btn-small {
            padding: 4px 8px;
            font-size: 12px;
        }

        .btn-success {
            background-color: #52c41a;
        }

        .btn-success:hover {
            background-color: #389e0d;
        }

        .btn-danger {
            background-color: #f5222d;
        }

        .btn-danger:hover {
            background-color: #cf1322;
        }

        /* 表单样式 */
        .form-container {
            max-width: 600px;
            margin: 20px auto;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            color: #575d6c;
        }

        .form-group input,
        .form-group select {
            width: 100%;
            padding: 10px;
            border: 1px solid #dfe1e6;
            border-radius: 4px;
            font-size: 14px;
            transition: all 0.2s;
        }

        .form-group input:focus,
        .form-group select:focus {
            outline: none;
            border-color: #1c2b36;
            box-shadow: 0 0 0 2px rgba(28, 43, 54, 0.1);
        }

        /* 状态标签样式 */
        .status-badge {
            display: inline-block;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
        }

        .status-active {
            background-color: #e6f7e6;
            color: #52c41a;
        }

        .status-inactive {
            background-color: #fff1f0;
            color: #f5222d;
        }

<<<<<<< HEAD
        /* 部��形结构样式 */
        .tree-container {
            padding: 20px;
        }

        .department-tree {
            list-style: none;
            padding: 0;
        }

        .tree-node {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 10px;
            margin: 5px 0;
            background: #f8f9fa;
            border-radius: 4px;
            transition: all 0.2s;
        }

        .tree-node:hover {
            background: #e9ecef;
        }

        .tree-node .department-info {
            display: flex;
            align-items: center;
            gap: 15px;
            color: #666;
            font-size: 14px;
        }

        .tree-node .manager {
            color: #1890ff;
        }

        .tree-node .no-manager {
            color: #ff4d4f;
        }

        .tree-node-actions {
            opacity: 0;
            transition: opacity 0.2s;
        }

        .tree-node:hover .tree-node-actions {
            opacity: 1;
        }

        .department-name {
            font-weight: bold;
        }

        .department-info {
            color: #666;
            font-size: 14px;
        }

        /* 表单样式补充 */
        .form-group textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #dfe1e6;
            border-radius: 4px;
            font-size: 14px;
            resize: vertical;
        }

        /* 照片预览样式 */
        .photo-preview {
            width: 100px;
            height: 100px;
            border: 1px solid #dfe1e6;
            border-radius: 4px;
            overflow: hidden;
        }

        .photo-preview-img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        /* 员工列表相关样式 */
        .search-section {
            background: white;
            padding: 15px;
            border-radius: 4px;
            margin-bottom: 20px;
        }

        .form-inline {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .status-warning {
            background-color: #fff7e6;
            color: #fa8c16;
        }

        /* 分页按钮样式 */
        .pagination .btn-small {
            padding: 4px 8px;
            margin: 0 2px;
        }

        .pagination .btn-small.active {
            background-color: #1c2b36;
            color: white;
        }

        .pagination .btn-small[disabled] {
            background-color: #f5f5f5;
            color: #999;
            cursor: not-allowed;
        }

        /* 员工详情样式 */
        .detail-container {
            background: white;
            padding: 20px;  /* 减小整体内边距 */
            border-radius: 8px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
        }

        /* 头部区域样式优化 */
        .employee-header {
            display: flex;
            align-items: center;
            gap: 30px;
            margin-bottom: 40px;
            padding-bottom: 30px;
            border-bottom: 1px solid #f0f0f0;
        }

        .employee-photo {
            width: 150px;
            height: 150px;
            border-radius: 75px;
            overflow: hidden;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }

        .employee-photo img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .employee-photo .no-photo {
            width: 100%;
            height: 100%;
            background: #f5f5f5;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #999;
            font-size: 14px;
        }

        .employee-basic-info h3 {
            margin: 0 0 15px 0;
            font-size: 28px;
            color: #1c2b36;
            font-weight: 500;
        }

        /* 信息网格布局优化 */
        .info-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 25px;
            margin-bottom: 40px;
        }

        .info-group {
            background: #fff;
            border-radius: 8px;
            padding: 15px;  /* 减小内边距 */
            margin-bottom: 15px;  /* 减小底部间距 */
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
        }

        .info-group:hover {
            background: #f3f4f6;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
        }

        .info-group h4 {
            color: #1c2b36;
            font-size: 16px;  /* 减小标题字体 */
            font-weight: 500;
            margin-bottom: 10px;  /* 减小标题底部间距 */
            padding-bottom: 8px;  /* 减小标题下边框间距 */
            border-bottom: 1px solid #f0f0f0;  /* 减小边框粗细 */
        }

        .info-item {
            display: flex;
            margin-bottom: 0;
            padding: 8px 12px;  /* 减小每项的内边距 */
            align-items: center;
            transition: background-color 0.2s;
        }

        .info-item label {
            color: #666;
            min-width: 80px;  /* 减小标签宽度 */
            font-size: 14px;  /* 减小字体大小 */
            font-weight: normal;
        }

        .info-item .info-value {
            color: #1c2b36;
            font-size: 14px;  /* 减小字体大小 */
            flex: 1;
            padding-left: 15px;  /* 减小左边距 */
        }

        /* 状态标签优化 */
        .status-badge {
            display: inline-block;
            padding: 4px 12px;  /* 减小内边距 */
            border-radius: 15px;
            font-size: 13px;
        }

        /* 按钮区域优化 */
        .action-buttons {
            display: flex;
            gap: 15px;
            justify-content: flex-end;
            padding-top: 20px;
            border-top: 1px solid #f0f0f0;
        }

        .action-buttons .btn {
            padding: 10px 24px;
            font-size: 15px;
            border-radius: 6px;
            transition: all 0.3s ease;
        }

        .action-buttons .btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }

        /* 响应式布局优化 */
        @media (max-width: 768px) {
            .info-grid {
                grid-template-columns: 1fr;
            }
            
            .employee-header {
                flex-direction: column;
                text-align: center;
            }
            
            .info-item {
                flex-direction: column;
            }
            
            .info-item label {
                margin-bottom: 5px;
            }
        }

        /* 员工详情页面布局优化 */
        .employee-detail-layout {
            display: flex;
            gap: 20px;  /* 减小左右两栏间距 */
            margin-bottom: 15px;  /* 减小底部间距 */
        }

        /* 左侧信息区域 */
        .employee-info-section {
            flex: 1;
            max-width: 65%;
        }

        .info-group {
            background: #fff;
            border-radius: 6px;
            padding: 12px;  /* 减小内边距 */
            margin-bottom: 12px;  /* 减小组件间距 */
            box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
        }

        .info-group h4 {
            color: #1c2b36;
            font-size: 15px;  /* 减小标题字体 */
            font-weight: 500;
            margin-bottom: 8px;  /* 减小标题底部间距 */
            padding-bottom: 6px;  /* 减小标题下边框间距 */
            border-bottom: 1px solid #f0f0f0;
        }

        .info-content {
            padding: 0;
        }

        .info-item {
            display: flex;
            padding: 6px 10px;  /* 减小每项的内边距 */
            align-items: center;
        }

        .info-item:nth-child(even) {
            background-color: #f8f9fa;
        }

        .info-item label {
            color: #666;
            min-width: 70px;  /* 减小标签宽度 */
            font-size: 13px;  /* 减小字体大小 */
        }

        .info-item .info-value {
            color: #1c2b36;
            font-size: 13px;  /* 减小字体大小 */
            flex: 1;
            padding-left: 10px;  /* 减小左边距 */
        }

        /* 右侧照片区域 */
        .employee-photo-section {
            width: 35%;
            padding: 12px;  /* 减小内边距 */
        }

        .employee-photo-large {
            width: 280px;  /* 稍微减小照片宽度 */
            height: 370px;  /* 稍微减小照片高度 */
            border-radius: 6px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }

        /* 备注文本样式 */
        .remark-text {
            color: #666;
            line-height: 1.4;
            font-size: 13px;
            padding: 8px;
            background: #f8f9fa;
            border-radius: 4px;
            margin: 0;
        }

        /* 状态标签优化 */
        .info-item .status-badge {
            padding: 3px 10px;
            border-radius: 12px;
            font-size: 12px;
        }

        /* 按钮区域 */
        .action-buttons {
            display: flex;
            gap: 12px;
            justify-content: flex-end;
            padding-top: 15px;
            margin-top: 15px;
            border-top: 1px solid #f0f0f0;
        }

        .action-buttons .btn {
            padding: 8px 20px;
            font-size: 14px;
        }

        /* 优化右侧照片区域样式 */
        .employee-photo-section {
            width: 35%;
            padding: 20px;
            display: flex;
            justify-content: center;
            align-items: flex-start;
        }

        .employee-photo-large {
            width: 360px;  /* 增加照片宽度 */
            height: 480px;  /* 增加照片高度 */
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
            background: #f8f9fa;
            transition: all 0.3s ease;
        }

        .employee-photo-large:hover {
            transform: scale(1.02);  /* 添加悬停效果 */
            box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
        }

        .employee-photo-large img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            display: block;
        }

        .employee-photo-large .no-photo {
            width: 100%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #999;
            font-size: 16px;
            background: #f5f5f5;
        }

        /* 调整左侧信息区域以适应更大的照片 */
        .employee-info-section {
            flex: 1;
            max-width: 60%;  /* 稍微减小左侧宽度 */
            padding-right: 20px;  /* 添加右侧间距 */
        }

        /* 导入导出相关样式 */
        .filter-group {
            display: flex;
            gap: 10px;
            margin-bottom: 15px;
        }

        .filter-group .form-control {
            flex: 1;
        }

        .alert {
            padding: 15px;
            border-radius: 4px;
            margin-bottom: 15px;
        }

        .alert-info {
            background-color: #e6f7ff;
            border: 1px solid #91d5ff;
            color: #1890ff;
        }

        .alert-success {
            background-color: #f6ffed;
            border: 1px solid #b7eb8f;
            color: #52c41a;
        }

        .alert-danger {
            background-color: #fff2f0;
            border: 1px solid #ffccc7;
            color: #ff4d4f;
        }

        .error-details {
            margin-top: 10px;
            padding: 10px;
            background: rgba(255, 77, 79, 0.1);
=======
        /* 部门形结构样式 */
        .tree-container {
            padding: 20px;
        }

        .department-tree {
            list-style: none;
            padding: 0;
        }

        .tree-node {
            padding: 8px;
            margin: 4px 0;
            background: #f8f9fa;
>>>>>>> 3c947f1aba3ee54d50472e0f837782629d528bae
            border-radius: 4px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .department-name {
            font-weight: bold;
        }

        .department-info {
            color: #666;
            font-size: 14px;
        }

        .error-details div {
            margin-bottom: 5px;
        }
    </style>
</head>
<body>
    <header class="header">
        <h1>人员管理系统</h1>
        <div class="user-info">
            <span class="username" id="username"></span>
            <span class="role" id="userRole"></span>
            <a href="javascript:void(0)" onclick="logout()" class="logout-btn">退出登录</a>
        </div>
    </header>

    <div class="main-container">
        <nav class="sidebar">
            <div class="nav-item active" onclick="showModule('auth', event)">用户认证</div>
<<<<<<< HEAD
            <div class="nav-item has-submenu" onclick="toggleSubmenu('employeeSubmenu', event)">员工管理</div>
            <div id="employeeSubmenu" class="nav-submenu">
                <div class="nav-item" onclick="showEmployeeContent('create', event)">创建员工</div>
                <div class="nav-item" onclick="showEmployeeContent('list', event)">员工列表</div>
                <div class="nav-item" onclick="showEmployeeContent('import', event)">员工导入</div>
                <div class="nav-item" onclick="showEmployeeContent('export', event)">员工导出</div>
            </div>
            <div class="nav-item has-submenu" onclick="toggleSubmenu('departmentSubmenu', event)">部门管理</div>
=======
            <div class="nav-item" onclick="showModule('employees', event)">员工管理</div>
            <div class="nav-item has-submenu" onclick="toggleSubmenu('departmentSubmenu', event)">
                部门管理
            </div>
>>>>>>> 3c947f1aba3ee54d50472e0f837782629d528bae
            <div id="departmentSubmenu" class="nav-submenu">
                <div class="nav-item" onclick="showDepartmentContent('create', event)">创建部门</div>
                <div class="nav-item" onclick="showDepartmentContent('list', event)">部门列表</div>
                <div class="nav-item" onclick="showDepartmentContent('tree', event)">部门结构</div>
<<<<<<< HEAD
            </div>
            <div class="nav-item has-submenu" onclick="toggleSubmenu('roleSubmenu', event)">角色管理</div>
            <div id="roleSubmenu" class="nav-submenu">
                <div class="nav-item" onclick="showRoleContent('create', event)">创建角色</div>
                <div class="nav-item" onclick="showRoleContent('list', event)">角色列表</div>
            </div>
            <div id="userManagementMenu" style="display: none;">
                <div class="nav-item has-submenu" onclick="toggleSubmenu('userSubmenu', event)">用户管理</div>
                <div id="userSubmenu" class="nav-submenu">
                    <div class="nav-item" onclick="showUserContent('create', event)">创建用户</div>
                    <div class="nav-item" onclick="showUserContent('list', event)">用户列表</div>
                    <div class="nav-item" onclick="showUserContent('operations', event)">用户日志</div>
=======
                <div class="nav-item" onclick="showDepartmentContent('detail', event)">部门详情</div>
                <div class="nav-item" onclick="showDepartmentContent('update', event)">更新部门</div>
                <div class="nav-item" onclick="showDepartmentContent('delete', event)">删除部门</div>
            </div>
            <div class="nav-item" onclick="showModule('roles', event)">角色管理</div>
            <div id="userManagementMenu" style="display: none;">
                <div class="nav-item has-submenu" onclick="toggleSubmenu('userSubmenu', event)">
                    用户管理
                </div>
                <div id="userSubmenu" class="nav-submenu">
                    <div class="nav-item" onclick="showUserContent('create', event)">创建用户</div>
                    <div class="nav-item" onclick="showUserContent('list', event)">用户列表</div>
                    <div class="nav-item" onclick="showUserContent('operations', event)">用户操作</div>
>>>>>>> 3c947f1aba3ee54d50472e0f837782629d528bae
                </div>
            </div>
        </nav>

        <main class="content" id="apiContent">
            <!-- 内容区域 -->
        </main>
    </div>

    <script>
        // 角色映射
        const roleMap = {
            1: "系统管理员",
            2: "部门主管",
            3: "普通用户"
        };

        // 页面加载时的初始化
        window.onload = function() {
            // 检查登录状态
            const token = sessionStorage.getItem('token');
            const username = sessionStorage.getItem('username');
            const roleId = parseInt(sessionStorage.getItem('roleId'));
            
            if (!token || !username) {
                window.location.href = '/';
                return;
            }

            // 显示用户信息
            const usernameElement = document.getElementById('username');
            const userRoleElement = document.getElementById('userRole');
            
            if (usernameElement && userRoleElement) {
                usernameElement.textContent = `欢迎，${username}`;
                userRoleElement.textContent = roleMap[roleId] || "未知角色";
            }

            // 如果是管理员，显示用户管理菜单
            if (roleId === 1) {
                document.getElementById('userManagementMenu').style.display = 'block';
            }

            // 显示默模块
            showModule('auth');
        }

        // 显示不同模块
        function showModule(module, event) {
            // 更新导航项状态
            document.querySelectorAll('.nav-item').forEach(item => {
                item.classList.remove('active');
            });
            if (event && event.currentTarget) {
                event.currentTarget.classList.add('active');
            }

            // 根据模块显示不同内容
            if (module === 'users') {
                showUserContent('list', event);
            } else {
                loadApiContent(module);
            }
        }

        // 切换子菜单显示/隐藏
        function toggleSubmenu(submenuId, event) {
            if (event) {
                event.stopPropagation();
            }
            const submenu = document.getElementById(submenuId);
            submenu.classList.toggle('show');
            if (event && event.currentTarget) {
                event.currentTarget.classList.toggle('expanded');
            }
        }

<<<<<<< HEAD
        // 示用户管理相关内容
=======
        // 显示用户管理相关内容
>>>>>>> 3c947f1aba3ee54d50472e0f837782629d528bae
        function showUserContent(type, event) {
            // 更新导航项状态
            document.querySelectorAll('.nav-item').forEach(item => {
                item.classList.remove('active');
            });
            if (event && event.currentTarget) {
                event.currentTarget.classList.add('active');
            }

            const content = document.getElementById('apiContent');
            
            switch(type) {
                case 'create':
                    content.innerHTML = `
                        <div class="content-section">
                            <h2>建新用户</h2>
                            <div class="form-container">
                                <form id="createUserForm" onsubmit="return handleCreateUser(event)">
                                    <div class="form-group">
                                        <label for="username">用户名</label>
                                        <input type="text" id="username" name="username" required>
                                    </div>
                                    <div class="form-group">
                                        <label for="password">密码</label>
                                        <input type="password" id="password" name="password" required>
                                    </div>
                                    <div class="form-group">
                                        <label for="role">角色</label>
                                        <select id="role" name="role_id" required>
                                            <option value="1">系统管理员</option>
                                            <option value="2">部门主管</option>
                                            <option value="3">普通用户</option>
                                        </select>
                                    </div>
                                    <div class="form-group">
                                        <label for="status">状态</label>
                                        <select id="status" name="status">
                                            <option value="1">启用</option>
                                            <option value="0">禁用</option>
                                        </select>
                                    </div>
                                    <button type="submit" class="btn">创建用户</button>
                                </form>
                            </div>
                        </div>
                    `;
                    break;
                    
                case 'list':
                    content.innerHTML = `
                        <div class="content-section">
                            <h2>用户列表</h2>
                            <div class="table-container">
                                <table class="data-table">
                                    <thead>
                                        <tr>
                                            <th>ID</th>
                                            <th>用户名</th>
                                            <th>角色</th>
                                            <th>状态</th>
                                            <th>创建时间</th>
                                            <th>操作</th>
                                        </tr>
                                    </thead>
                                    <tbody id="userTableBody">
                                        <!-- 用户数据将通过 API 动态加载 -->
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    `;
                    loadUserList();
                    break;
                    
                case 'operations':
                    content.innerHTML = `
                        <div class="content-section">
                            <h2>用户操作</h2>
                            
                            <!-- 搜索区域 -->
                            <div class="search-section">
                                <form id="searchForm" onsubmit="return handleSearch(event)">
                                    <div class="form-group">
                                        <input type="text" id="keyword" placeholder="输入用户名搜索...">
                                    </div>
                                    <div class="form-group">
                                        <select id="roleFilter">
                                            <option value="">所有角色</option>
                                            <option value="1">系统管理员</option>
                                            <option value="2">部门主管</option>
                                            <option value="3">普通用户</option>
                                        </select>
                                    </div>
                                    <div class="form-group">
                                        <select id="statusFilter">
                                            <option value="">所有状态</option>
                                            <option value="1">启用</option>
                                            <option value="0">禁用</option>
                                        </select>
                                    </div>
                                    <button type="submit" class="btn">搜索</button>
                                </form>
                            </div>

                            <!-- 搜索结果区域 -->
                            <div id="searchResults" class="table-container">
                                <!-- 搜索结果将动态加载到这里 -->
                            </div>

                            <!-- 用户日志区域 -->
                            <div id="userLogs" class="logs-container" style="display: none;">
                                <h3>用户操作日志</h3>
                                <div class="table-container">
                                    <table class="data-table">
                                        <thead>
                                            <tr>
                                                <th>时间</th>
                                                <th>操作</th>
                                                <th>IP地址</th>
                                                <th>详情</th>
                                            </tr>
                                        </thead>
                                        <tbody id="userLogsBody">
                                            <!-- 日志数据将动态加载到这里 -->
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    `;
                    break;
            }
        }

        // 处理创建用户
        async function handleCreateUser(event) {
            event.preventDefault();
            const form = event.target;
            const formData = new FormData(form);
            
            // 转换数据格式
            const data = {
                username: formData.get('username'),
                password: formData.get('password'),
                role_id: parseInt(formData.get('role_id')),
                status: parseInt(formData.get('status'))
            };
            
            try {
                const response = await fetch('/api/users', {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${sessionStorage.getItem('token')}`,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(data)
                });
                
                if (!response.ok) {
                    const errorData = await response.json();
                    throw new Error(errorData.detail || '创建用户失败');
                }
                
                await response.json();
                alert('用户创建成功');
                form.reset();
                showUserContent('list');
                
            } catch (error) {
                console.error('创建用户错误:', error);
                alert(error.message || '创建用户失败，请稍后重试');
            }
        }

        // 加载用户列表
        async function loadUserList() {
            const token = sessionStorage.getItem('token');
            try {
                const response = await fetch('/api/users', {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                
                if (response.ok) {
                    const users = await response.json();
                    const tbody = document.getElementById('userTableBody');
                    tbody.innerHTML = users.map(user => {
                        // 添加调试日志
                        console.log('User data:', user);
                        console.log('Create time before format:', user.create_time);
                        const formattedTime = formatDate(user.create_time);
                        console.log('Formatted time:', formattedTime);
                        
                        return `
                            <tr>
                                <td>${user.id}</td>
                                <td>${user.username}</td>
                                <td>${roleMap[user.role_id] || '未知角色'}</td>
                                <td>
                                    <span class="status-badge ${user.status === 1 ? 'status-active' : 'status-inactive'}">
                                        ${user.status === 1 ? '启用' : '禁用'}
                                    </span>
                                </td>
                                <td>${formattedTime}</td>
                                <td>
                                    <button onclick="editUser(${user.id})" class="btn-small">编辑</button>
                                    <button onclick="toggleUserStatus(${user.id}, ${user.status})" 
                                            class="btn-small ${user.status === 1 ? 'btn-danger' : 'btn-success'}">
                                        ${user.status === 1 ? '禁用' : '启用'}
                                    </button>
                                </td>
                            </tr>
                        `;
                    }).join('');
<<<<<<< HEAD
                }
            } catch (error) {
                console.error('加载用户���表失败:', error);
            }
        }

        // ��式化时间显示
        function formatDate(dateString) {
            if (!dateString) {
                console.log('Empty date string');
                return '无数据';
            }
            
            try {
                console.log('Formatting date:', dateString);
                // 试解析不同格式的时间字符串
                let date;
                if (dateString.includes('T')) {
                    // ISO 格式: "2024-01-17T08:30:00"
                    date = new Date(dateString);
                } else if (dateString.includes('+')) {
                    // 带区的格式: "2024-01-17 08:30:00+00:00"
                    date = new Date(dateString.split('+')[0].trim());
                } else {
                    // 普通格式: "2024-01-17 08:30:00"
                    date = new Date(dateString.replace(' ', 'T'));
                }

                // 检日期是否有效
                if (isNaN(date.getTime())) {
                    console.error('Invalid date:', dateString);
                    return '格式错误';
                }

                // 格式化为本地时间字串
                const options = {
                    year: 'numeric',
                    month: '2-digit',
                    day: '2-digit',
                    hour: '2-digit',
                    minute: '2-digit',
                    second: '2-digit',
                    hour12: false
                };

                return date.toLocaleString('zh-CN', options);
            } catch (error) {
                console.error('Date formatting error:', error, dateString);
                return '���间格式错误';
            }
        }

        // 退出登录
        function logout() {
            sessionStorage.clear();
            window.location.href = '/';
        }

        // 编辑用户
        async function editUser(userId) {
            const token = sessionStorage.getItem('token');
            try {
                // 获取用户信息
                const response = await fetch(`/api/users/${userId}`, {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                
                if (response.ok) {
                    const user = await response.json();
                    // 显示编辑表单
                    const content = document.getElementById('apiContent');
                    content.innerHTML = `
                        <div class="content-section">
                            <h2>编辑用户</h2>
                            <div class="form-container">
                                <form id="editUserForm" onsubmit="return handleEditUser(event, ${userId})">
                                    <div class="form-group">
                                        <label>用户名</label>
                                        <input type="text" value="${user.username}" disabled>
                                    </div>
                                    <div class="form-group">
                                        <label for="password">新密码</label>
                                        <input type="password" id="password" name="password">
                                        <small>留空表���不修改密码</small>
                                    </div>
                                    <div class="form-group">
                                        <label for="role">角色</label>
                                        <select id="role" name="role_id">
                                            <option value="1" ${user.role_id === 1 ? 'selected' : ''}>统管理员</option>
                                            <option value="2" ${user.role_id === 2 ? 'selected' : ''}>部门主管</option>
                                            <option value="3" ${user.role_id === 3 ? 'selected' : ''}>普通户</option>
                                        </select>
                                    </div>
                                    <div class="form-group">
                                        <label for="status">状态</label>
                                        <select id="status" name="status">
                                            <option value="1" ${user.status === 1 ? 'selected' : ''}>启用</option>
                                            <option value="0" ${user.status === 0 ? 'selected' : ''}>禁用</option>
                                        </select>
                                    </div>
                                    <button type="submit" class="btn">保存修改</button>
                                    <button type="button" class="btn btn-secondary" onclick="showUserContent('list')">取消</button>
                                </form>
                            </div>
                        </div>
                    `;
                }
            } catch (error) {
                console.error('加载用户信息失败:', error);
                alert('加载用户失败');
            }
        }

        // 理编辑用户
        async function handleEditUser(event, userId) {
            event.preventDefault();
            const form = event.target;
            const formData = new FormData(form);
            const data = {};
            
            // 只包含已修改的字段
            if (formData.get('password')) {
                data.password = formData.get('password');
            }
            if (formData.get('role_id')) {
                data.role_id = parseInt(formData.get('role_id'));
            }
            if (formData.get('status')) {
                data.status = parseInt(formData.get('status'));
            }
            
            try {
                const response = await fetch(`/api/users/${userId}`, {
                    method: 'PUT',
                    headers: {
                        'Authorization': `Bearer ${sessionStorage.getItem('token')}`,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(data)
                });
                
                if (response.ok) {
                    alert('用户信息更新成功');
                    showUserContent('list');
                } else {
                    const error = await response.json();
                    alert(error.detail || '更新用户信息失败');
                }
            } catch (error) {
                console.error('更新用户信息失败:', error);
                alert('更新用户信息失败，请稍后重试');
            }
        }

        // 切换用户状态
        async function toggleUserStatus(userId, currentStatus) {
            if (!confirm(`确定要${currentStatus === 1 ? '禁用' : '启用'}该用户吗？`)) {
                return;
            }
            
            try {
                const response = await fetch(`/api/users/${userId}/status`, {
                    method: 'PATCH',
                    headers: {
                        'Authorization': `Bearer ${sessionStorage.getItem('token')}`
                    }
                });
                
                if (response.ok) {
                    alert('用户状态更新成功');
                    showUserContent('list');  // 刷新列表
                } else {
                    const error = await response.json();
                    alert(error.detail || '更新用户状态失败');
                }
            } catch (error) {
                console.error('更新��户状态失败:', error);
                alert('更新用户状态失败，请稍后重试');
            }
        }

        // 处理搜索
        async function handleSearch(event) {
            event.preventDefault();
            const keyword = document.getElementById('keyword').value;
            const roleId = document.getElementById('roleFilter').value;
            const status = document.getElementById('statusFilter').value;

            const searchData = {
                keyword: keyword || undefined,
                role_id: roleId ? parseInt(roleId) : undefined,
                status: status ? parseInt(status) : undefined
            };

            try {
                const response = await fetch('/api/users/search', {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${sessionStorage.getItem('token')}`,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(searchData)
                });

                if (response.ok) {
                    const users = await response.json();
                    displaySearchResults(users);
                } else {
                    const error = await response.json();
                    alert(error.detail || '搜索失败');
                }
            } catch (error) {
                console.error('搜索失败:', error);
                alert('搜索失败，请稍后重试');
            }
        }

        // 显示搜索结果
        function displaySearchResults(users) {
            const resultsDiv = document.getElementById('searchResults');
            // 清除之前的日志显示
            document.getElementById('userLogs').style.display = 'none';
            
            if (users.length === 0) {
                resultsDiv.innerHTML = '<p>没有找到匹配的用户</p>';
                return;
            }

            resultsDiv.innerHTML = `
                <table class="data-table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>用户名</th>
                            <th>角色</th>
                            <th>状态</th>
                            <th>创建时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        ${users.map(user => `
                            <tr>
                                <td>${user.id}</td>
                                <td>${user.username}</td>
                                <td>${roleMap[user.role_id] || '未知角色'}</td>
                                <td>
                                    <span class="status-badge ${user.status === 1 ? 'status-active' : 'status-inactive'}">
                                        ${user.status === 1 ? '启用' : '禁用'}
                                    </span>
                                </td>
                                <td>${formatDate(user.create_time)}</td>
                                <td>
                                    <button onclick="viewUserLogs(${user.id}, '${user.username}')" class="btn-small">查看日志</button>
                                </td>
                            </tr>
                        `).join('')}
                    </tbody>
                </table>
            `;
        }

        // 查看用户日志
        async function viewUserLogs(userId, username) {
            try {
                const response = await fetch(`/api/users/${userId}/logs`, {
                    headers: {
                        'Authorization': `Bearer ${sessionStorage.getItem('token')}`
                    }
                });

                if (response.ok) {
                    const logs = await response.json();
                    displayUserLogs(logs, username);
                } else {
                    const error = await response.json();
                    alert(error.detail || '获取日志失败');
                }
            } catch (error) {
                console.error('获取日志失败:', error);
                alert('获取日志失败，请稍后重试');
            }
        }

        // 显示用户日志
        function displayUserLogs(logs, username) {
            const logsDiv = document.getElementById('userLogs');
            logsDiv.innerHTML = `
                <h3>${username} 的操作日志</h3>
                <div class="table-container">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>时间</th>
                                <th>操作</th>
                                <th>IP地址</th>
                                <th>详情</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${logs.map(log => `
                                <tr>
                                    <td>${formatDate(log.action_time)}</td>
                                    <td>${log.action}</td>
                                    <td>${log.ip_address || '-'}</td>
                                    <td>${log.details || '-'}</td>
                                </tr>
                            `).join('')}
                        </tbody>
                    </table>
                </div>
            `;
            logsDiv.style.display = 'block';
        }

        // 加载 API 内容
        async function loadApiContent(module) {
            const content = document.getElementById('apiContent');
            const token = sessionStorage.getItem('token');
            
            switch(module) {
                case 'auth':
                    try {
                        const response = await fetch('/api/auth/me', {
                            headers: {
                                'Authorization': `Bearer ${token}`
                            }
                        });
                        
                        if (response.ok) {
                            const user = await response.json();
                            console.log('User data:', user);  // 添加调试日志
                            
                            content.innerHTML = `
                                <div class="content-section">
                                    <h2>用户认证</h2>
                                    <div class="table-container">
                                        <table class="data-table">
                                            <thead>
                                                <tr>
                                                    <th>用户名</th>
                                                    <th>角色</th>
                                                    <th>状态</th>
                                                    <th>创建时间</th>
                                                    <th>最后更新时间</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <tr>
                                                    <td>${user.username}</td>
                                                    <td>${roleMap[user.role_id] || '未知角色'}</td>
                                                    <td>
                                                        <span class="status-badge ${user.status === 1 ? 'status-active' : 'status-inactive'}">
                                                            ${user.status === 1 ? '启用' : '禁用'}
                                                        </span>
                                                    </td>
                                                    <td>${user.create_time ? formatDate(user.create_time) : '无数据'}</td>
                                                    <td>${user.update_time ? formatDate(user.update_time) : '无数据'}</td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            `;
                        } else {
                            const error = await response.json();
                            content.innerHTML = `<div class="error">获取用户信息失败: ${error.detail}</div>`;
                        }
                    } catch (error) {
                        console.error('获取用户信息失败:', error);
                        content.innerHTML = '<div class="error">获取用户信息失败</div>';
                    }
                    break;
                    
                // ... 其他 case 保持不变 ...
            }
        }

        // 显示部门管理相关内容
        function showDepartmentContent(type, event) {
            // 更新导航项状态
            document.querySelectorAll('.nav-item').forEach(item => {
                item.classList.remove('active');
            });
            if (event && event.currentTarget) {
                event.currentTarget.classList.add('active');
            }

            const content = document.getElementById('apiContent');
            
            switch(type) {
                case 'create':
                    content.innerHTML = `
                        <div class="content-section">
                            <h2>创建部门</h2>
                            <div class="form-container">
                                <form id="createDepartmentForm" onsubmit="return handleCreateDepartment(event)">
                                    <div class="form-group">
                                        <label for="parent">上级部门</label>
                                        <select id="parent" name="parent_id">
                                            <option value="">无</option>
                                        </select>
                                    </div>
                                    <div class="form-group">
                                        <label for="name">门名称</label>
                                        <input type="text" id="name" name="name" required>
                                    </div>
                                    <div class="form-group">
                                        <label for="manager">部门主管</label>
                                        <select id="manager" name="manager_id">
                                            <option value="">暂不设置</option>
                                        </select>
                                    </div>
                                    <div class="form-group">
                                        <label for="description">部门描述</label>
                                        <textarea id="description" name="description" rows="3"></textarea>
                                    </div>
                                    <div class="form-group">
                                        <label for="status">状态</label>
                                        <select id="status" name="status">
                                            <option value="1">启用</option>
                                            <option value="0">禁用</option>
                                        </select>
                                    </div>
                                    <button type="submit" class="btn">创建部门</button>
                                </form>
                            </div>
                        </div>
                    `;
                    loadParentDepartmentOptions();  // 加载部门项
                    loadEmployeeOptions();    // 加载员工选项
                    break;
                    
                case 'list':
                    content.innerHTML = `
                        <div class="content-section">
                            <h2>部门列表</h2>
                            <div class="table-container">
                                <table class="data-table">
                                    <thead>
                                        <tr>
                                            <th>ID</th>
                                            <th>部门名称</th>
                                            <th>上级部门</th>
                                            <th>部门主管</th>
                                            <th>状态</th>
                                            <th>创建时间</th>
                                            <th>操作</th>
                                        </tr>
                                    </thead>
                                    <tbody id="departmentTableBody">
                                        <!-- 部门数据将通过 API 动态加载 -->
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    `;
                    loadDepartmentList();
                    break;
                    
                case 'tree':
                    content.innerHTML = `
                        <div class="content-section">
                            <h2>部门结构</h2>
                            <div class="tree-container" id="departmentTree">
                                <!-- 部门树形结构将通过 API 态加载 -->
                            </div>
                        </div>
                    `;
                    loadDepartmentTree();
                    break;
            }
        }

        // 加载部门列表
        async function loadDepartmentList() {
            const token = sessionStorage.getItem('token');
            try {
                const response = await fetch('/api/departments', {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                
                if (response.ok) {
                    const departments = await response.json();
                    const tbody = document.getElementById('departmentTableBody');
                    tbody.innerHTML = departments.map(dept => `
                        <tr>
                            <td>${dept.id}</td>
                            <td>${dept.name}</td>
                            <td>${dept.parent_name || '-'}</td>
                            <td>${dept.manager_name || '-'}</td>
                            <td>
                                <span class="status-badge ${dept.status === 1 ? 'status-active' : 'status-inactive'}">
                                    ${dept.status === 1 ? '启用' : '禁用'}
                                </span>
                            </td>
                            <td>${formatDate(dept.create_time)}</td>
                            <td>
                                <button onclick="editDepartment(${dept.id})" class="btn-small">编辑</button>
                                <button onclick="deleteDepartment(${dept.id})" class="btn-small btn-danger">删除</button>
                            </td>
                        </tr>
                    `).join('');
=======
>>>>>>> 3c947f1aba3ee54d50472e0f837782629d528bae
                }
            } catch (error) {
                console.error('加载部门列表失败:', error);
            }
        }

<<<<<<< HEAD
        // 加载部门树形结构
        async function loadDepartmentTree() {
            const token = sessionStorage.getItem('token');
            try {
                const response = await fetch('/api/departments/tree', {
=======
        // 格式化时间显示
        function formatDate(dateString) {
            if (!dateString) {
                console.log('Empty date string');
                return '无数据';
            }
            
            try {
                console.log('Formatting date:', dateString);
                // 尝试解析不同格式的时间字符串
                let date;
                if (dateString.includes('T')) {
                    // ISO 格式: "2024-01-17T08:30:00"
                    date = new Date(dateString);
                } else if (dateString.includes('+')) {
                    // 带时区的格式: "2024-01-17 08:30:00+00:00"
                    date = new Date(dateString.split('+')[0].trim());
                } else {
                    // 普通格式: "2024-01-17 08:30:00"
                    date = new Date(dateString.replace(' ', 'T'));
                }

                // 检查日期是否有效
                if (isNaN(date.getTime())) {
                    console.error('Invalid date:', dateString);
                    return '格式错误';
                }

                // 格式化为本地时间字串
                const options = {
                    year: 'numeric',
                    month: '2-digit',
                    day: '2-digit',
                    hour: '2-digit',
                    minute: '2-digit',
                    second: '2-digit',
                    hour12: false
                };

                return date.toLocaleString('zh-CN', options);
            } catch (error) {
                console.error('Date formatting error:', error, dateString);
                return '时间格式错误';
            }
        }

        // 退出登录
        function logout() {
            sessionStorage.clear();
            window.location.href = '/';
        }

        // 编辑用户
        async function editUser(userId) {
            const token = sessionStorage.getItem('token');
            try {
                // 获取用户信息
                const response = await fetch(`/api/users/${userId}`, {
>>>>>>> 3c947f1aba3ee54d50472e0f837782629d528bae
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                
                if (response.ok) {
<<<<<<< HEAD
                    const tree = await response.json();
                    const treeContainer = document.getElementById('departmentTree');
                    treeContainer.innerHTML = renderDepartmentTree(tree);
                }
            } catch (error) {
                console.error('加载部门树形结构失败:', error);
            }
        }

        // 渲染部门树形结构
        function renderDepartmentTree(departments, level = 0) {
            if (!departments || departments.length === 0) return '';
            
            const indent = level * 20;  // ���级缩进 20px
            return `
                <ul class="department-tree" style="margin-left: ${indent}px">
                    ${departments.map(dept => `
                        <li>
                            <div class="tree-node">
                                <span class="department-name">${dept.name}</span>
                                <span class="department-info">
                                    ${dept.manager_name ? 
                                        `<span class="manager">主管: ${dept.manager_name}</span>` : 
                                        '<span class="no-manager">未设置主管</span>'
                                    }
                                    <span class="employee-count">(${dept.employee_count}人)</span>
                                    <span class="status-badge ${dept.status === 1 ? 'status-active' : 'status-inactive'}">
                                        ${dept.status === 1 ? '正常' : '已禁用'}
                                    </span>
                                </span>
                                <div class="tree-node-actions">
                                    <button onclick="editDepartment(${dept.id})" class="btn-small">编辑</button>
                                    <button onclick="viewDepartmentDetail(${dept.id})" class="btn-small">详情</button>
                                </div>
                            </div>
                            ${renderDepartmentTree(dept.children, level + 1)}
                        </li>
                    `).join('')}
                </ul>
            `;
        }

        // 处理创建部门
        async function handleCreateDepartment(event) {
            event.preventDefault();
            const form = event.target;
            const formData = new FormData(form);
            const data = {
                name: formData.get('name'),
                parent_id: formData.get('parent_id') || null,
                manager_id: formData.get('manager_id') || null,
                description: formData.get('description'),
                status: parseInt(formData.get('status'))
            };
            
            try {
=======
                    const user = await response.json();
                    // 显示编辑表单
                    const content = document.getElementById('apiContent');
                    content.innerHTML = `
                        <div class="content-section">
                            <h2>编辑用户</h2>
                            <div class="form-container">
                                <form id="editUserForm" onsubmit="return handleEditUser(event, ${userId})">
                                    <div class="form-group">
                                        <label>用户名</label>
                                        <input type="text" value="${user.username}" disabled>
                                    </div>
                                    <div class="form-group">
                                        <label for="password">新密码</label>
                                        <input type="password" id="password" name="password">
                                        <small>留空表示不修改密码</small>
                                    </div>
                                    <div class="form-group">
                                        <label for="role">角色</label>
                                        <select id="role" name="role_id">
                                            <option value="1" ${user.role_id === 1 ? 'selected' : ''}>系统管理员</option>
                                            <option value="2" ${user.role_id === 2 ? 'selected' : ''}>部门主管</option>
                                            <option value="3" ${user.role_id === 3 ? 'selected' : ''}>普通户</option>
                                        </select>
                                    </div>
                                    <div class="form-group">
                                        <label for="status">状态</label>
                                        <select id="status" name="status">
                                            <option value="1" ${user.status === 1 ? 'selected' : ''}>启用</option>
                                            <option value="0" ${user.status === 0 ? 'selected' : ''}>禁用</option>
                                        </select>
                                    </div>
                                    <button type="submit" class="btn">保存修改</button>
                                    <button type="button" class="btn btn-secondary" onclick="showUserContent('list')">取消</button>
                                </form>
                            </div>
                        </div>
                    `;
                }
            } catch (error) {
                console.error('加载用户信息失败:', error);
                alert('加载用户失败');
            }
        }

        // 处理编辑用户
        async function handleEditUser(event, userId) {
            event.preventDefault();
            const form = event.target;
            const formData = new FormData(form);
            const data = {};
            
            // 只包含已修改的字段
            if (formData.get('password')) {
                data.password = formData.get('password');
            }
            if (formData.get('role_id')) {
                data.role_id = parseInt(formData.get('role_id'));
            }
            if (formData.get('status')) {
                data.status = parseInt(formData.get('status'));
            }
            
            try {
                const response = await fetch(`/api/users/${userId}`, {
                    method: 'PUT',
                    headers: {
                        'Authorization': `Bearer ${sessionStorage.getItem('token')}`,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(data)
                });
                
                if (response.ok) {
                    alert('用户信息更新成功');
                    showUserContent('list');
                } else {
                    const error = await response.json();
                    alert(error.detail || '更新用户信息失败');
                }
            } catch (error) {
                console.error('更新用户信息失败:', error);
                alert('更新用户信息失败，请稍后重试');
            }
        }

        // 切换用户状态
        async function toggleUserStatus(userId, currentStatus) {
            if (!confirm(`确定要${currentStatus === 1 ? '禁用' : '启用'}该用户吗？`)) {
                return;
            }
            
            try {
                const response = await fetch(`/api/users/${userId}/status`, {
                    method: 'PATCH',
                    headers: {
                        'Authorization': `Bearer ${sessionStorage.getItem('token')}`
                    }
                });
                
                if (response.ok) {
                    alert('用户状态更新成功');
                    showUserContent('list');  // 刷新列表
                } else {
                    const error = await response.json();
                    alert(error.detail || '更新用户状态失败');
                }
            } catch (error) {
                console.error('更新用户状态失败:', error);
                alert('更新用户状态失败，请稍后重试');
            }
        }

        // 处理搜索
        async function handleSearch(event) {
            event.preventDefault();
            const keyword = document.getElementById('keyword').value;
            const roleId = document.getElementById('roleFilter').value;
            const status = document.getElementById('statusFilter').value;

            const searchData = {
                keyword: keyword || undefined,
                role_id: roleId ? parseInt(roleId) : undefined,
                status: status ? parseInt(status) : undefined
            };

            try {
                const response = await fetch('/api/users/search', {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${sessionStorage.getItem('token')}`,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(searchData)
                });

                if (response.ok) {
                    const users = await response.json();
                    displaySearchResults(users);
                } else {
                    const error = await response.json();
                    alert(error.detail || '搜索失败');
                }
            } catch (error) {
                console.error('搜索失败:', error);
                alert('搜索失败，请稍后重试');
            }
        }

        // 显示搜索结果
        function displaySearchResults(users) {
            const resultsDiv = document.getElementById('searchResults');
            // 清除之前的日志显示
            document.getElementById('userLogs').style.display = 'none';
            
            if (users.length === 0) {
                resultsDiv.innerHTML = '<p>没有找到匹配的用户</p>';
                return;
            }

            resultsDiv.innerHTML = `
                <table class="data-table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>用户名</th>
                            <th>角色</th>
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        ${users.map(user => `
                            <tr>
                                <td>${user.id}</td>
                                <td>${user.username}</td>
                                <td>${roleMap[user.role_id] || '未知角色'}</td>
                                <td>
                                    <span class="status-badge ${user.status === 1 ? 'status-active' : 'status-inactive'}">
                                        ${user.status === 1 ? '启用' : '禁用'}
                                    </span>
                                </td>
                                <td>
                                    <button onclick="viewUserLogs(${user.id}, '${user.username}')" class="btn-small">查看日志</button>
                                </td>
                            </tr>
                        `).join('')}
                    </tbody>
                </table>
            `;
        }

        // 查看用户日志
        async function viewUserLogs(userId, username) {
            try {
                const response = await fetch(`/api/users/${userId}/logs`, {
                    headers: {
                        'Authorization': `Bearer ${sessionStorage.getItem('token')}`
                    }
                });

                if (response.ok) {
                    const logs = await response.json();
                    displayUserLogs(logs, username);
                } else {
                    const error = await response.json();
                    alert(error.detail || '获取日志失败');
                }
            } catch (error) {
                console.error('获取日志失败:', error);
                alert('获取日志失败，请稍后重试');
            }
        }

        // 显示用户日志
        function displayUserLogs(logs, username) {
            const logsDiv = document.getElementById('userLogs');
            logsDiv.innerHTML = `
                <h3>${username} 的操作日志</h3>
                <div class="table-container">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>时间</th>
                                <th>操作</th>
                                <th>IP地址</th>
                                <th>详情</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${logs.map(log => `
                                <tr>
                                    <td>${formatDate(log.action_time)}</td>
                                    <td>${log.action}</td>
                                    <td>${log.ip_address || '-'}</td>
                                    <td>${log.details || '-'}</td>
                                </tr>
                            `).join('')}
                        </tbody>
                    </table>
                </div>
            `;
            logsDiv.style.display = 'block';
        }

        // 加载 API 内容
        async function loadApiContent(module) {
            const content = document.getElementById('apiContent');
            const token = sessionStorage.getItem('token');
            
            switch(module) {
                case 'auth':
                    try {
                        const response = await fetch('/api/auth/me', {
                            headers: {
                                'Authorization': `Bearer ${token}`
                            }
                        });
                        
                        if (response.ok) {
                            const user = await response.json();
                            console.log('User data:', user);  // 添加调试日志
                            
                            content.innerHTML = `
                                <div class="content-section">
                                    <h2>用户认证</h2>
                                    <div class="table-container">
                                        <table class="data-table">
                                            <thead>
                                                <tr>
                                                    <th>用户名</th>
                                                    <th>角色</th>
                                                    <th>状态</th>
                                                    <th>创建时间</th>
                                                    <th>最后更新时间</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <tr>
                                                    <td>${user.username}</td>
                                                    <td>${roleMap[user.role_id] || '未知角色'}</td>
                                                    <td>
                                                        <span class="status-badge ${user.status === 1 ? 'status-active' : 'status-inactive'}">
                                                            ${user.status === 1 ? '启用' : '禁用'}
                                                        </span>
                                                    </td>
                                                    <td>${user.create_time ? formatDate(user.create_time) : '无数据'}</td>
                                                    <td>${user.update_time ? formatDate(user.update_time) : '无数据'}</td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            `;
                        } else {
                            const error = await response.json();
                            content.innerHTML = `<div class="error">获取用户信息失败: ${error.detail}</div>`;
                        }
                    } catch (error) {
                        console.error('获取用户信息失败:', error);
                        content.innerHTML = '<div class="error">获取用户信息失败</div>';
                    }
                    break;
                    
                // ... 其他 case 保持不变 ...
            }
        }

        // 显示部门管理相关内容
        function showDepartmentContent(type, event) {
            // 更新导航项状态
            document.querySelectorAll('.nav-item').forEach(item => {
                item.classList.remove('active');
            });
            if (event && event.currentTarget) {
                event.currentTarget.classList.add('active');
            }

            const content = document.getElementById('apiContent');
            
            switch(type) {
                case 'create':
                    content.innerHTML = `
                        <div class="content-section">
                            <h2>创建部门</h2>
                            <div class="form-container">
                                <form id="createDepartmentForm" onsubmit="return handleCreateDepartment(event)">
                                    <div class="form-group">
                                        <label for="name">部门名称</label>
                                        <input type="text" id="name" name="name" required>
                                    </div>
                                    <div class="form-group">
                                        <label for="parent">上级部门</label>
                                        <select id="parent" name="parent_id">
                                            <option value="">无</option>
                                            <!-- 部门选项将通过 API 动态加载 -->
                                        </select>
                                    </div>
                                    <div class="form-group">
                                        <label for="manager">部门主管</label>
                                        <select id="manager" name="manager_id">
                                            <option value="">暂不设置</option>
                                            <!-- 员工选项将通过 API 动态加载 -->
                                        </select>
                                    </div>
                                    <div class="form-group">
                                        <label for="description">部门描述</label>
                                        <textarea id="description" name="description" rows="3"></textarea>
                                    </div>
                                    <div class="form-group">
                                        <label for="status">状态</label>
                                        <select id="status" name="status">
                                            <option value="1">启用</option>
                                            <option value="0">禁用</option>
                                        </select>
                                    </div>
                                    <button type="submit" class="btn">创建部门</button>
                                </form>
                            </div>
                        </div>
                    `;
                    loadDepartmentOptions();
                    loadEmployeeOptions();
                    break;
                    
                case 'list':
                    content.innerHTML = `
                        <div class="content-section">
                            <h2>部门列表</h2>
                            <div class="table-container">
                                <table class="data-table">
                                    <thead>
                                        <tr>
                                            <th>ID</th>
                                            <th>部门名称</th>
                                            <th>上级部门</th>
                                            <th>部门主管</th>
                                            <th>状态</th>
                                            <th>创建时间</th>
                                            <th>操作</th>
                                        </tr>
                                    </thead>
                                    <tbody id="departmentTableBody">
                                        <!-- 部门数据将通过 API 动态加载 -->
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    `;
                    loadDepartmentList();
                    break;
                    
                case 'tree':
                    content.innerHTML = `
                        <div class="content-section">
                            <h2>部门结构</h2>
                            <div class="tree-container" id="departmentTree">
                                <!-- 部门树形结构将通过 API 动态加载 -->
                            </div>
                        </div>
                    `;
                    loadDepartmentTree();
                    break;
            }
        }

        // 加载部门列表
        async function loadDepartmentList() {
            const token = sessionStorage.getItem('token');
            try {
                const response = await fetch('/api/departments', {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                
                if (response.ok) {
                    const departments = await response.json();
                    const tbody = document.getElementById('departmentTableBody');
                    tbody.innerHTML = departments.map(dept => `
                        <tr>
                            <td>${dept.id}</td>
                            <td>${dept.name}</td>
                            <td>${dept.parent_name || '-'}</td>
                            <td>${dept.manager_name || '-'}</td>
                            <td>
                                <span class="status-badge ${dept.status === 1 ? 'status-active' : 'status-inactive'}">
                                    ${dept.status === 1 ? '启用' : '禁用'}
                                </span>
                            </td>
                            <td>${formatDate(dept.create_time)}</td>
                            <td>
                                <button onclick="editDepartment(${dept.id})" class="btn-small">编辑</button>
                                <button onclick="deleteDepartment(${dept.id})" class="btn-small btn-danger">删除</button>
                            </td>
                        </tr>
                    `).join('');
                }
            } catch (error) {
                console.error('加载部门列表失败:', error);
            }
        }

        // 加载部门树形结构
        async function loadDepartmentTree() {
            const token = sessionStorage.getItem('token');
            try {
                const response = await fetch('/api/departments/tree', {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                
                if (response.ok) {
                    const tree = await response.json();
                    const treeContainer = document.getElementById('departmentTree');
                    treeContainer.innerHTML = renderDepartmentTree(tree);
                }
            } catch (error) {
                console.error('加载部门树形结构失败:', error);
            }
        }

        // 渲染部门树形结构
        function renderDepartmentTree(departments, level = 0) {
            if (!departments || departments.length === 0) return '';
            
            const indent = level * 20;  // 每级缩进 20px
            return `
                <ul class="department-tree" style="margin-left: ${indent}px">
                    ${departments.map(dept => `
                        <li>
                            <div class="tree-node">
                                <span class="department-name">${dept.name}</span>
                                <span class="department-info">
                                    [主管: ${dept.manager_name || '未设置'}]
                                    (${dept.employee_count}人)
                                </span>
                            </div>
                            ${renderDepartmentTree(dept.children, level + 1)}
                        </li>
                    `).join('')}
                </ul>
            `;
        }

        // 处理创建部门
        async function handleCreateDepartment(event) {
            event.preventDefault();
            const form = event.target;
            const formData = new FormData(form);
            const data = {
                name: formData.get('name'),
                parent_id: formData.get('parent_id') || null,
                manager_id: formData.get('manager_id') || null,
                description: formData.get('description'),
                status: parseInt(formData.get('status'))
            };
            
            try {
>>>>>>> 3c947f1aba3ee54d50472e0f837782629d528bae
                const response = await fetch('/api/departments', {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${sessionStorage.getItem('token')}`,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(data)
                });
                
                if (response.ok) {
                    alert('部门创建成功');
                    form.reset();
                    showDepartmentContent('list');
                } else {
                    const error = await response.json();
                    alert(error.detail || '创建部门失败');
                }
            } catch (error) {
                console.error('创建部门失败:', error);
                alert('创建部门失败，请稍后重试');
            }
        }

        // 编辑部门
        async function editDepartment(deptId) {
            const token = sessionStorage.getItem('token');
            try {
<<<<<<< HEAD
                
=======
>>>>>>> 3c947f1aba3ee54d50472e0f837782629d528bae
                const response = await fetch(`/api/departments/${deptId}`, {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                
                if (response.ok) {
                    const dept = await response.json();
                    const content = document.getElementById('apiContent');
                    content.innerHTML = `
                        <div class="content-section">
                            <h2>编辑部门</h2>
                            <div class="form-container">
                                <form id="editDepartmentForm" onsubmit="return handleEditDepartment(event, ${deptId})">
                                    <div class="form-group">
                                        <label for="name">部门名称</label>
                                        <input type="text" id="name" name="name" value="${dept.name}" required>
                                    </div>
                                    <div class="form-group">
                                        <label for="parent">上级部门</label>
                                        <select id="parent" name="parent_id">
                                            <option value="">无</option>
                                            <!-- 部门选项将通过 API 动态加载 -->
                                        </select>
                                    </div>
                                    <div class="form-group">
                                        <label for="manager">部门主管</label>
                                        <select id="manager" name="manager_id">
                                            <option value="">暂不设置</option>
                                            <!-- 员工选项将通过 API 动态加载 -->
                                        </select>
                                    </div>
                                    <div class="form-group">
                                        <label for="description">部门描述</label>
                                        <textarea id="description" name="description" rows="3">${dept.description || ''}</textarea>
                                    </div>
                                    <div class="form-group">
                                        <label for="status">状态</label>
                                        <select id="status" name="status">
                                            <option value="1" ${dept.status === 1 ? 'selected' : ''}>启用</option>
                                            <option value="0" ${dept.status === 0 ? 'selected' : ''}>禁用</option>
                                        </select>
                                    </div>
                                    <button type="submit" class="btn">保存修改</button>
                                    <button type="button" class="btn btn-secondary" onclick="showDepartmentContent('list')">取消</button>
                                </form>
                            </div>
                        </div>
                    `;
<<<<<<< HEAD
                    
                    loadEmployeeOptions();
                    // loadParentDepartmentOptions(dept.id);
                    loadParentDepartmentOptions(dept.id);
                    // 设置当前
=======
                    loadDepartmentOptions(dept.id);
                    loadEmployeeOptions();
                    // 设置当前值
>>>>>>> 3c947f1aba3ee54d50472e0f837782629d528bae
                    document.getElementById('parent').value = dept.parent_id || '';
                    document.getElementById('manager').value = dept.manager_id || '';
                }
            } catch (error) {
<<<<<<< HEAD
                console.error('加载部门信息��败:', error);
=======
                console.error('加载部门信息失败:', error);
>>>>>>> 3c947f1aba3ee54d50472e0f837782629d528bae
                alert('加载部门信息失败');
            }
        }

        // 处理编辑部门
        async function handleEditDepartment(event, deptId) {
            event.preventDefault();
            const form = event.target;
            const formData = new FormData(form);
            const data = {
                name: formData.get('name'),
                parent_id: formData.get('parent_id') || null,
                manager_id: formData.get('manager_id') || null,
                description: formData.get('description'),
                status: parseInt(formData.get('status'))
            };
<<<<<<< HEAD
            
            try {
                const response = await fetch(`/api/departments/${deptId}`, {
                    method: 'PUT',
                    headers: {
                        'Authorization': `Bearer ${sessionStorage.getItem('token')}`,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(data)
                });
                
                if (response.ok) {
                    alert('部门信息更新成功');
                    showDepartmentContent('list');
                } else {
                    const error = await response.json();
                    alert(error.detail || '更新部门信息失败');
                }
            } catch (error) {
                console.error('更新部门信息失败:', error);
                alert('更新部门信息失败，请稍后重试');
            }
        }

        // 删除部门
        async function deleteDepartment(deptId) {
            // 先检查部门是否有子部门或关联员工
            try {
                const checkResponse = await fetch(`/api/departments/${deptId}/check`, {
                    headers: {
                        'Authorization': `Bearer ${sessionStorage.getItem('token')}`
                    }
                });
                
                const checkResult = await checkResponse.json();
                
                if (checkResult.hasChildren) {
                    alert('该部门下还有子部门,请先处理子部门');
                    return;
                }
                
                if (checkResult.hasEmployees) {
                    alert('该部门下还有员工,请先调整员工所属部门');
                    return;  
                }
                
                if (!confirm('确定要删除该部门吗？此操作不可恢复！')) {
                    return;
                }
                
                const response = await fetch(`/api/departments/${deptId}`, {
                    method: 'DELETE',
                    headers: {
                        'Authorization': `Bearer ${sessionStorage.getItem('token')}`
                    }
                });
                
                if (response.ok) {
                    alert('部门删除成功');
                    showDepartmentContent('list');
                } else {
                    const error = await response.json();
                    throw new Error(error.detail || '删除部门失败');
                }
            } catch (error) {
                console.error('删除部门失败:', error);
                alert(error.message || '删除部门失败,请稍后重试');
            }
        }

        // 加载部门选项
        async function loadDepartmentOptions(excludeId = null) {
            const select = document.getElementById('parent');
            select.disabled = true; // 添加加载状态
            
            try {
                const response = await fetch('/api/departments', {
                    headers: {
                        'Authorization': `Bearer ${sessionStorage.getItem('token')}`,
                        'Content-Type': 'application/json'
                    }
                });
                
                if (!response.ok) {
                    throw new Error('加载部门数据失败');
                }
                
                const departments = await response.json();
                
                select.innerHTML = '<option value="">无</option>';
                if (Array.isArray(departments) && departments.length > 0) {
                    const filteredDepts = excludeId 
                        ? departments.filter(dept => String(dept.id) !== String(excludeId))
                        : departments;
                    
                    select.innerHTML += filteredDepts
                        .map(dept => `<option value="${dept.id}">${dept.name}</option>`)
                        .join('');
                }
            } catch (error) {
                console.error('加载部门选项失败:', error);
                alert('加载部门选项失败,请��新重试');
            } finally {
                select.disabled = false; // 恢复���选状态
            }
        }

        // 加载员工选项
        async function loadEmployeeOptions() {
            console.log('开始加载员工选项'); 
            const token = sessionStorage.getItem('token');
            try {
                const response = await fetch('/api/employees', {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                
                if (response.ok) {
                    const employees = await response.json();
                    const select = document.getElementById('manager');
                    select.innerHTML = '<option value="">暂不设置</option>' +
                        employees.map(emp => `
                            <option value="${emp.id}">${emp.name}</option>
                        `).join('');
                }
            } catch (error) {
                console.error('加载员工选项失败:', error);
            }
        }

        // 显示���工管理相关内容
        function showEmployeeContent(type, event) {
            // 更新导航项状态
            document.querySelectorAll('.nav-item').forEach(item => {
                item.classList.remove('active');
            });
            if (event && event.currentTarget) {
                event.currentTarget.classList.add('active');
            }

            const content = document.getElementById('apiContent');
            
            switch(type) {
                case 'create':
                    content.innerHTML = `
                        <div class="content-section">
                            <h2>创建员工</h2>
                            <div class="form-container">
                                <form id="createEmployeeForm" onsubmit="return handleCreateEmployee(event)">
                                    <!-- 基本信息 -->
                                    <div class="form-group">
                                        <label for="name">姓名</label>
                                        <input type="text" id="name" name="name" required>
                                    </div>
                                    <div class="form-group">
                                        <label for="gender">性别</label>
                                        <select id="gender" name="gender" required>
                                            <option value="1">男</option>
                                            <option value="2">女</option>
                                        </select>
                                    </div>
                                    <div class="form-group">
                                        <label for="birth_date">出生日期</label>
                                        <input type="date" id="birth_date" name="birth_date" required>
                                    </div>
                                    <div class="form-group">
                                        <label for="id_card">身份证号</label>
                                        <input type="text" id="id_card" name="id_card">
                                    </div>
                                    <div class="form-group">
                                        <label for="phone">手机号</label>
                                        <input type="tel" id="phone" name="phone" required>
                                    </div>
                                    <div class="form-group">
                                        <label for="address">住址</label>
                                        <input type="text" id="address" name="address">
                                    </div>

                                    <!-- 工作信息 -->
                                    <div class="form-group">
                                        <label for="department">所属部门</label>
                                        <select id="department" name="department_id" required>
                                            <option value="">请选择部门</option>
                                        </select>
                                    </div>
                                    <div class="form-group">
                                        <label for="position">职位</label>
                                        <input type="text" id="position" name="position" required>
                                    </div>
                                    <div class="form-group">
                                        <label for="status">状态</label>
                                        <select id="status" name="status">
                                            <option value="1">在职</option>
                                            <option value="2">离职</option>
                                            <option value="3">试用期</option>
                                        </select>
                                    </div>

                                    <!-- 照片上传 -->
                                    <div class="form-group">
                                        <label for="photo">照</label>
                                        <input type="file" id="photo" name="photo" accept="image/*" onchange="previewPhoto(event)">
                                        <div id="photoPreview" class="photo-preview"></div>
                                    </div>

                                    <!-- 紧急联系人 -->
                                    <div class="form-group">
                                        <label for="emergency_contact">紧急联系人</label>
                                        <input type="text" id="emergency_contact" name="emergency_contact">
                                    </div>
                                    <div class="form-group">
                                        <label for="emergency_phone">紧急联系电话</label>
                                        <input type="tel" id="emergency_phone" name="emergency_phone">
                                    </div>

                                    <!-- 备注 -->
                                    <div class="form-group">
                                        <label for="remark">备注</label>
                                        <textarea id="remark" name="remark" rows="3"></textarea>
                                    </div>

                                    <button type="submit" class="btn">创建员工</button>
                                </form>
                            </div>
                        </div>
                    `;
                    loadDepartmentOptions();  // 加载部门选项
                    break;
                    
                case 'list':
                    content.innerHTML = `
                        <div class="content-section">
                            <h2>员工列表</h2>
                            
                            <!-- 搜索区域 -->
                            <div class="search-section" style="margin-bottom: 20px;">
                                <form id="employeeSearchForm" class="form-inline" onsubmit="return handleEmployeeSearch(event)">
                                    <div class="form-group" style="display: inline-block; margin-right: 10px;">
                                        <input type="text" id="nameSearch" placeholder="姓名搜索" class="form-control">
                                    </div>
                                    <div class="form-group" style="display: inline-block; margin-right: 10px;">
                                        <select id="departmentSearch" class="form-control">
                                            <option value="">所有部门</option>
                                        </select>
                                    </div>
                                    <div class="form-group" style="display: inline-block; margin-right: 10px;">
                                        <select id="statusSearch" class="form-control">
                                            <option value="">所有状态</option>
                                            <option value="1">在职</option>
                                            <option value="2">离职</option>
                                            <option value="3">试用期</option>
                                        </select>
                                    </div>
                                    <button type="submit" class="btn">搜索</button>
                                </form>
                            </div>

                            <!-- 表格区域 -->
                            <div class="table-container">
                                <table class="data-table">
                                    <thead>
                                        <tr>
                                            <th>照片</th>
                                            <th>姓名</th>
                                            <th>部门</th>
                                            <th>职位</th>
                                            <th>手机号</th>
                                            <th>状态</th>
                                            <th>入职时间</th>
                                            <th>操作</th>
                                        </tr>
                                    </thead>
                                    <tbody id="employeeTableBody">
                                        <!-- 员工数据将通过 API 动态加载 -->
                                    </tbody>
                                </table>
                            </div>

                            <!-- 分页区域 -->
                            <div class="pagination" id="employeePagination" style="margin-top: 20px; text-align: center;">
                                <!-- 分页控件将动态生成 -->
                            </div>
                        </div>
                    `;
                    
                    // 加载部门选项到搜索框
                    loadDepartmentSearchOptions();
                    // 加载员工数据
                    loadEmployeeList();
                    break;

                case 'import':
                    content.innerHTML = `
                        <div class="content-section">
                            <h2>导入员工信息</h2>
                            <div class="form-container">
                                <form id="importForm" onsubmit="return handleImportEmployees(event)">
                                    <div class="form-group">
                                        <label for="importFile">选择Excel文件</label>
                                        <input type="file" id="importFile" name="file" accept=".xlsx" required>
                                        <small class="form-text">请上传 .xlsx 格式的Excel文件</small>
                                    </div>
                                    <div class="form-group">
                                        <a href="/static/templates/employee_import_template.xlsx" class="btn btn-secondary">
                                            下载导入模板
                                        </a>
                                    </div>
                                    <button type="submit" class="btn">开始导入</button>
                                </form>
                                <div id="importResult" style="margin-top: 20px;"></div>
                            </div>
                        </div>
                    `;
                    break;

                case 'export':
                    content.innerHTML = `
                        <div class="content-section">
                            <h2>导出员工信息</h2>
                            
                            <!-- 搜索区域 -->
                            <div class="search-section" style="margin-bottom: 20px; background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
                                <form id="exportForm" class="form-inline">
                                    <div class="form-group" style="display: inline-block; margin-right: 10px;">
                                        <input type="text" id="exportNameSearch" placeholder="姓名搜索" class="form-control">
                                    </div>
                                    <div class="form-group" style="display: inline-block; margin-right: 10px;">
                                        <select id="exportDepartmentSearch" class="form-control">
                                            <option value="">所有部门</option>
                                        </select>
                                    </div>
                                    <div class="form-group" style="display: inline-block; margin-right: 10px;">
                                        <select id="exportStatusSearch" class="form-control">
                                            <option value="">所有状态</option>
                                            <option value="1">在职</option>
                                            <option value="2">离职</option>
                                            <option value="3">试用期</option>
                                        </select>
                                    </div>
                                    <button type="button" onclick="searchExportEmployees()" class="btn">搜索</button>
                                </form>
                            </div>

                            <!-- 预览表格区域 -->
                            <div class="content-section" style="background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
                                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
                                    <span id="exportCount" style="color: #666;"></span>
                                    <button type="button" onclick="handleExportEmployees()" class="btn">导出Excel</button>
                                </div>
                                
                                <div class="table-container">
                                    <table class="data-table">
                                        <thead>
                                            <tr>
                                                <th>照片</th>
                                                <th>姓名</th>
                                                <th>部门</th>
                                                <th>职位</th>
                                                <th>手机号</th>
                                                <th>状态</th>
                                                <th>入职时间</th>
                                            </tr>
                                        </thead>
                                        <tbody id="exportPreviewBody">
                                            <!-- 员工数据将动态加载 -->
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    `;
                    // 加载部门选项
                    loadDepartmentSearchOptions();
                    break;
            }
        }

        // 处理创建员工
        async function handleCreateEmployee(event) {
            event.preventDefault();
            const form = event.target;
            const formData = new FormData(form);
            
            try {
                // 先处理照片上传
                const photoFile = formData.get('photo');
                let photoUrl = null;
                
                if (photoFile && photoFile.size > 0) {
                    const photoFormData = new FormData();
                    photoFormData.append('photo', photoFile);
                    
                    const photoResponse = await fetch('/api/employees/upload-photo', {
                        method: 'POST',
                        headers: {
                            'Authorization': `Bearer ${sessionStorage.getItem('token')}`
                        },
                        body: photoFormData
                    });
                    
                    if (photoResponse.ok) {
                        const photoData = await photoResponse.json();
                        photoUrl = photoData.url;  // 直接使用后端返回的URL，不做替换
                    }
                }
                
                // 构建员工数据
                const employeeData = {
                    name: formData.get('name'),
                    gender: parseInt(formData.get('gender')),
                    birth_date: formData.get('birth_date'),
                    id_card: formData.get('id_card') || null,
                    phone: formData.get('phone'),
                    address: formData.get('address') || null,
                    department_id: parseInt(formData.get('department_id')) || null,
                    position: formData.get('position'),
                    status: parseInt(formData.get('status')),
                    emergency_contact: formData.get('emergency_contact') || null,
                    emergency_phone: formData.get('emergency_phone') || null,
                    remark: formData.get('remark') || null,
                    photo_url: null  // 初始化为 null，后面会根据情况更新
                };
                
                // 创建员工
                const response = await fetch('/api/employees', {
                    method: 'POST',
=======
            
            try {
                const response = await fetch(`/api/departments/${deptId}`, {
                    method: 'PUT',
>>>>>>> 3c947f1aba3ee54d50472e0f837782629d528bae
                    headers: {
                        'Authorization': `Bearer ${sessionStorage.getItem('token')}`,
                        'Content-Type': 'application/json'
                    },
<<<<<<< HEAD
                    body: JSON.stringify(employeeData)
                });
                
                if (response.ok) {
                    alert('员工创建成功');
                    form.reset();
                    showEmployeeContent('list');
                } else {
                    const error = await response.json();
                    alert(error.detail || '创建员工失败');
                }
            } catch (error) {
                console.error('创建员工失败:', error);
                alert('创建员工失败，请稍后重试');
            }
        }

        // 照片预览
        function previewPhoto(event) {
            const file = event.target.files[0];
            const preview = document.getElementById('photoPreview');
            
            if (file) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    preview.innerHTML = `<img src="${e.target.result}" class="photo-preview-img">`;
                };
                reader.readAsDataURL(file);
            } else {
                preview.innerHTML = '';
            }
        }

        // 创建员工时使用的部门加载函数
        async function loadDepartmentOptions() {
            const token = sessionStorage.getItem('token');
            try {
                const response = await fetch('/api/departments', {
                    headers: {
                        'Authorization': `Bearer ${token}`
=======
                    body: JSON.stringify(data)
                });
                
                if (response.ok) {
                    alert('部门信息更新成功');
                    showDepartmentContent('list');
                } else {
                    const error = await response.json();
                    alert(error.detail || '更新部门信息失败');
                }
            } catch (error) {
                console.error('更新部门信息失败:', error);
                alert('更新部门信息失败，请稍后重试');
            }
        }

        // 删除部门
        async function deleteDepartment(deptId) {
            if (!confirm('确定要删除该部门吗？此操作不可恢复！')) {
                return;
            }
            
            try {
                const response = await fetch(`/api/departments/${deptId}`, {
                    method: 'DELETE',
                    headers: {
                        'Authorization': `Bearer ${sessionStorage.getItem('token')}`
>>>>>>> 3c947f1aba3ee54d50472e0f837782629d528bae
                    }
                });
                
                if (response.ok) {
<<<<<<< HEAD
                    const departments = await response.json();
                    const select = document.getElementById('department');
                    
                    select.innerHTML = '<option value="">请选择部门</option>' +
                        departments.map(dept => `
                            <option value="${dept.id}">${dept.name}</option>
                        `).join('');
                }
            } catch (error) {
                console.error('加载部门选项失败:', error);
            }
        }

        // 创建/编辑部门时使用的上级部门加载函数
        async function loadParentDepartmentOptions(currentDeptId = null) {
=======
                    alert('部门删除成功');
                    showDepartmentContent('list');
                } else {
                    const error = await response.json();
                    alert(error.detail || '删除部门失败');
                }
            } catch (error) {
                console.error('删除部门失败:', error);
                alert('删除部门失败，请稍后重试');
            }
        }

        // 加载部门选项
        async function loadDepartmentOptions(excludeId = null) {
>>>>>>> 3c947f1aba3ee54d50472e0f837782629d528bae
            const token = sessionStorage.getItem('token');
            try {
                const response = await fetch('/api/departments', {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                
                if (response.ok) {
                    const departments = await response.json();
                    const select = document.getElementById('parent');
<<<<<<< HEAD
                    
                    // 基础选项
                    let options = '<option value="">无</option>';
                    
                    // 如果有部门数据，添加可选部门
                    if (departments && departments.length > 0) {
                        options += departments
                            // 过滤掉当前部门（如果有）
                            .filter(dept => !currentDeptId || dept.id != currentDeptId)
                            .map(dept => `
                                <option value="${dept.id}">${dept.name}</option>
                            `).join('');
                    }
                    
                    select.innerHTML = options;
                }
            } catch (error) {
                console.error('加载上级部门选项失败:', error);
            }
        }

        // 加载员工列表数据
        async function loadEmployeeList(page = 1) {
            const token = sessionStorage.getItem('token');
            const tbody = document.getElementById('employeeTableBody');
            
            // 添加加载中提示
            tbody.innerHTML = '<tr><td colspan="8" style="text-align: center;">加���中...</td></tr>';
            
            try {
                // 获取搜索条件
                const nameSearch = document.getElementById('nameSearch')?.value || '';
                const departmentSearch = document.getElementById('departmentSearch')?.value || '';
                const statusSearch = document.getElementById('statusSearch')?.value || '';

                // 构建查询参数
                const params = new URLSearchParams({
                    page,
                    name: nameSearch,
                    department_id: departmentSearch,
                    status: statusSearch
                });

                const response = await fetch(`/api/employees?${params}`, {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                
                if (!response.ok) {
                    throw new Error('获取员工数据失败');
                }
                
                const data = await response.json();
                console.log('API返回的数据:', data); // 添加调试日志
                
                // 处理不同的数据格式
                let employees = [];
                let total = 0;
                
                if (Array.isArray(data)) {
                    // 如果直接返回数组
                    employees = data;
                    total = data.length;
                } else if (data.items && Array.isArray(data.items)) {
                    // 如果返回分页格式
                    employees = data.items;
                    total = data.total;
                } else if (data.data && Array.isArray(data.data)) {
                    // 如果返回 {data: [...]} 格式
                    employees = data.data;
                    total = data.total || data.data.length;
                } else {
                    throw new Error('未知的数据格式');
                }
                
                // 渲染员工数据
                tbody.innerHTML = employees.length ? 
                    employees.map(employee => `
                        <tr>
                            <td>
                                ${employee.photo_url ? 
                                    `<img src="${employee.photo_url}" 
                                        alt="员工照片" 
                                        style="width: 40px; height: 40px; border-radius: 50%; object-fit: cover;">` :
                                    '<div style="width: 40px; height: 40px; border-radius: 50%; background: #f0f0f0; display: flex; align-items: center; justify-content: center;">无</div>'
                                }
                            </td>
                            <td>${employee.name || '-'}</td>
                            <td>${employee.department_name || '-'}</td>
                            <td>${employee.position || '-'}</td>
                            <td>${employee.phone || '-'}</td>
                            <td>
                                <span class="status-badge ${getStatusClass(employee.status)}">
                                    ${getStatusText(employee.status)}
                                </span>
                            </td>
                            <td>${employee.create_time ? formatDate(employee.create_time) : '-'}</td>
                            <td>
                                <button onclick="viewEmployee(${employee.id})" class="btn-small">查看</button>
                                <button onclick="editEmployee(${employee.id})" class="btn-small">编辑</button>
                                <button onclick="deleteEmployee(${employee.id})" class="btn-small btn-danger">删除</button>
                            </td>
                        </tr>
                    `).join('') :
                    '<tr><td colspan="8" style="text-align: center;">暂无数据</td></tr>';

                // 更新分页
                if (total > 0) {
                    updatePagination(total, page);
                } else {
                    document.getElementById('employeePagination').innerHTML = '';
                }
                
            } catch (error) {
                console.error('加载员工列表失败:', error);
                console.log('详细错误信息:', error.message); // 添加详细错误信息
                tbody.innerHTML = '<tr><td colspan="8" style="text-align: center; color: #f5222d;">加载失败，请刷新重试</td></tr>';
                alert('加载员工列表失败，请稍后重试');
            }
        }

        // 获取状态样式类
        function getStatusClass(status) {
            switch(parseInt(status)) {
                case 1: return 'status-active';   // 在职
                case 2: return 'status-inactive'; // 职
                case 3: return 'status-warning';  // 试用期
                default: return '';
            }
        }

        // 获取状态文本
        function getStatusText(status) {
            switch(parseInt(status)) {
                case 1: return '在职';
                case 2: return '离职';
                case 3: return '试用期';
                default: return '未知';
            }
        }

        // 更新分页控件
        function updatePagination(total, currentPage) {
            const pageSize = 10; // 每页显示数量
            const totalPages = Math.ceil(total / pageSize);
            const pagination = document.getElementById('employeePagination');
            
            let paginationHtml = '';
            
            // 上一页
            paginationHtml += `
                <button onclick="loadEmployeeList(${currentPage - 1})" 
                        class="btn-small" 
                        ${currentPage === 1 ? 'disabled' : ''}>
                    上一页
                </button>
            `;
            
            // 页码
            for (let i = 1; i <= totalPages; i++) {
                paginationHtml += `
                    <button onclick="loadEmployeeList(${i})" 
                            class="btn-small ${currentPage === i ? 'active' : ''}"
                            style="margin: 0 5px;">
                        ${i}
                    </button>
                `;
            }
            
            // 下一页
            paginationHtml += `
                <button onclick="loadEmployeeList(${currentPage + 1})" 
                        class="btn-small"
                        ${currentPage === totalPages ? 'disabled' : ''}>
                    下一页
                </button>
            `;
            
            pagination.innerHTML = paginationHtml;
        }

        // 添加加载部门搜索选项的函数
        async function loadDepartmentSearchOptions() {
            const token = sessionStorage.getItem('token');
            try {
                const response = await fetch('/api/departments', {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                
                if (response.ok) {
                    const departments = await response.json();
                    const select = document.getElementById('departmentSearch');
                    
                    if (select) {
                        select.innerHTML = '<option value="">所有部门</option>' +
                            departments.map(dept => `
                                <option value="${dept.id}">${dept.name}</option>
                            `).join('');
                    }
=======
                    select.innerHTML = '<option value="">无</option>' +
                        departments
                            .filter(dept => dept.id !== excludeId)  // 排除当前部门
                            .map(dept => `
                                <option value="${dept.id}">${dept.name}</option>
                            `).join('');
>>>>>>> 3c947f1aba3ee54d50472e0f837782629d528bae
                }
            } catch (error) {
                console.error('加载部门选项失败:', error);
            }
        }

<<<<<<< HEAD
        // 添加搜索处理函数
        async function handleEmployeeSearch(event) {
            event.preventDefault();
            await loadEmployeeList(1); // 重置到第一页并加载数据
            return false;
        }

        // 查看员工详情
        async function viewEmployee(employeeId) {
            const token = sessionStorage.getItem('token');
            try {
                const response = await fetch(`/api/employees/${employeeId}`, {
=======
        // 加载员工选项
        async function loadEmployeeOptions() {
            const token = sessionStorage.getItem('token');
            try {
                const response = await fetch('/api/employees', {
>>>>>>> 3c947f1aba3ee54d50472e0f837782629d528bae
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                
                if (response.ok) {
<<<<<<< HEAD
                    const employee = await response.json();
                    const content = document.getElementById('apiContent');
                    
                    content.innerHTML = `
                        <div class="content-section">
                            <h2>员工详情</h2>
                            <div class="detail-container">
                                <div class="employee-detail-layout">
                                    <!-- 左侧信息区域 -->
                                    <div class="employee-info-section">
                                        <!-- 基本信息 -->
                                        <div class="info-group">
                                            <h4>基本信息</h4>
                                            <div class="info-content">
                                                <div class="info-item">
                                                    <label>姓名:</label>
                                                    <span class="info-value">${employee.name}</span>
                                                </div>
                                                <div class="info-item">
                                                    <label>性别:</label>
                                                    <span class="info-value">${employee.gender === 1 ? '男' : '女'}</span>
                                                </div>
                                                <div class="info-item">
                                                    <label>出生日期:</label>
                                                    <span class="info-value">${employee.birth_date || '-'}</span>
                                                </div>
                                                <div class="info-item">
                                                    <label>身份证号:</label>
                                                    <span class="info-value">${employee.id_card || '-'}</span>
                                                </div>
                                                <div class="info-item">
                                                    <label>手机号:</label>
                                                    <span class="info-value">${employee.phone || '-'}</span>
                                                </div>
                                                <div class="info-item">
                                                    <label>住址:</label>
                                                    <span class="info-value">${employee.address || '-'}</span>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- 工作信息 -->
                                        <div class="info-group">
                                            <h4>工作信息</h4>
                                            <div class="info-content">
                                                <div class="info-item">
                                                    <label>所属部门:</label>
                                                    <span class="info-value">${employee.department_name || '-'}</span>
                                                </div>
                                                <div class="info-item">
                                                    <label>职位:</label>
                                                    <span class="info-value">${employee.position || '-'}</span>
                                                </div>
                                                <div class="info-item">
                                                    <label>入职时间:</label>
                                                    <span class="info-value">${formatDate(employee.create_time)}</span>
                                                </div>
                                                <div class="info-item">
                                                    <label>状态:</label>
                                                    <span class="status-badge ${getStatusClass(employee.status)}">
                                                        ${getStatusText(employee.status)}
                                                    </span>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- 紧急联系人 -->
                                        <div class="info-group">
                                            <h4>紧急联系人</h4>
                                            <div class="info-content">
                                                <div class="info-item">
                                                    <label>姓名:</label>
                                                    <span class="info-value">${employee.emergency_contact || '-'}</span>
                                                </div>
                                                <div class="info-item">
                                                    <label>电话:</label>
                                                    <span class="info-value">${employee.emergency_phone || '-'}</span>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- 备注 -->
                                        <div class="info-group">
                                            <h4>备注</h4>
                                            <div class="info-content">
                                                <p class="remark-text">${employee.remark || '无'}</p>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- 右侧照片区域 -->
                                    <div class="employee-photo-section">
                                        <div class="employee-photo-large">
                                            ${employee.photo_url ? 
                                                `<img src="${employee.photo_url}" alt="员工照片">` :
                                                '<div class="no-photo">暂无照片</div>'
                                            }
                                        </div>
                                    </div>
                                </div>

                                <!-- 底部按钮 -->
                                <div class="action-buttons">
                                    <button onclick="editEmployee(${employee.id})" class="btn">编辑</button>
                                    <button onclick="showEmployeeContent('list')" class="btn btn-secondary">返回</button>
                                </div>
                            </div>
                        </div>
                    `;
                }
            } catch (error) {
                console.error('加载员工详情失败:', error);
                alert('加载员工详情失败，���稍后重试');
            }
        }

        // 编辑员工信息
        async function editEmployee(employeeId) {
            const token = sessionStorage.getItem('token');
            try {
                const response = await fetch(`/api/employees/${employeeId}`, {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                
                if (response.ok) {
                    const employee = await response.json();
                    const content = document.getElementById('apiContent');
                    
                    content.innerHTML = `
                        <div class="content-section">
                            <h2>编辑员工信息</h2>
                            <div class="form-container">
                                <form id="editEmployeeForm" onsubmit="return handleEditEmployee(event, ${employeeId})">
                                    <!-- 基信息 -->
                                    <div class="form-group">
                                        <label for="name">姓名</label>
                                        <input type="text" id="name" name="name" value="${employee.name}" required>
                                    </div>
                                    <div class="form-group">
                                        <label for="gender">性别</label>
                                        <select id="gender" name="gender" required>
                                            <option value="1" ${employee.gender === 1 ? 'selected' : ''}>男</option>
                                            <option value="2" ${employee.gender === 2 ? 'selected' : ''}>女</option>
                                        </select>
                                    </div>
                                    <div class="form-group">
                                        <label for="birth_date">出生日期</label>
                                        <input type="date" id="birth_date" name="birth_date" value="${employee.birth_date}" required>
                                    </div>
                                    <div class="form-group">
                                        <label for="id_card">身份证号</label>
                                        <input type="text" id="idcard" name="id_card" value="${employee.id_card || ''}">
                                    </div>
                                    <div class="form-group">
                                        <label for="phone">手机号</label>
                                        <input type="tel" id="phone" name="phone" value="${employee.phone}" required>
                                    </div>
                                    <div class="form-group">
                                        <label for="address">住址</label>
                                        <input type="text" id="address" name="address" value="${employee.address || ''}">
                                    </div>

                                    <!-- 工作信息 -->
                                    <div class="form-group">
                                        <label for="department">所属部门</label>
                                        <select id="department" name="department_id" required>
                                            <option value="">请选择部门</option>
                                        </select>
                                    </div>
                                    <div class="form-group">
                                        <label for="position">职位</label>
                                        <input type="text" id="position" name="position" value="${employee.position}" required>
                                    </div>
                                    <div class="form-group">
                                        <label for="status">状态</label>
                                        <select id="status" name="status">
                                            <option value="1" ${employee.status === 1 ? 'selected' : ''}>在职</option>
                                            <option value="2" ${employee.status === 2 ? 'selected' : ''}>离职</option>
                                            <option value="3" ${employee.status === 3 ? 'selected' : ''}>试用期</option>
                                        </select>
                                    </div>

                                    <!-- 照片上传 -->
                                    <div class="form-group">
                                        <label for="photo">照片</label>
                                        <input type="file" id="photo" name="photo" accept="image/*" onchange="previewPhoto(event)">
                                        <div id="photoPreview" class="photo-preview">
                                            ${employee.photo_url ? 
                                                `<img src="${employee.photo_url}" class="photo-preview-img">` : 
                                                ''}
                                        </div>
                                    </div>

                                    <!-- 紧急联系人 -->
                                    <div class="form-group">
                                        <label for="emergency_contact">紧急联系人</label>
                                        <input type="text" id="emergency_contact" name="emergency_contact" 
                                            value="${employee.emergency_contact || ''}">
                                    </div>
                                    <div class="form-group">
                                        <label for="emergency_phone">紧急联系电话</label>
                                        <input type="tel" id="emergency_phone" name="emergency_phone" 
                                            value="${employee.emergency_phone || ''}">
                                    </div>

                                    <!-- 备注 -->
                                    <div class="form-group">
                                        <label for="remark">备注</label>
                                        <textarea id="remark" name="remark" rows="3">${employee.remark || ''}</textarea>
                                    </div>

                                    <div class="form-buttons">
                                        <button type="submit" class="btn">保存修改</button>
                                        <button type="button" class="btn btn-secondary" onclick="showEmployeeContent('list')">取消</button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    `;
                    
                    // 加载部门选项并设置当前部门
                    await loadDepartmentOptions();
                    if (employee.department_id) {
                        document.getElementById('department').value = employee.department_id;
                    }
                }
            } catch (error) {
                console.error('加载员工信息失败:', error);
                alert('加载员工信息失败，请稍后重试');
            }
        }

        // 修改处理编辑员工表单提交的函数
        async function handleEditEmployee(event, employeeId) {
            event.preventDefault();
            const form = event.target;
            const formData = new FormData(form);
            
            try {
                // 先获取当前员工信息（包含旧照片URL）
                const currentResponse = await fetch(`/api/employees/${employeeId}`, {
                    headers: {
                        'Authorization': `Bearer ${sessionStorage.getItem('token')}`
                    }
                });
                
                if (!currentResponse.ok) {
                    throw new Error('获取当前员工信息失败');
                }
                
                const currentEmployee = await currentResponse.json();
                const oldPhotoUrl = currentEmployee.photo_url;  // 保存旧照片URL

                // 构建基本的员工数据
                const employeeData = {
                    name: formData.get('name'),
                    gender: parseInt(formData.get('gender')),
                    birth_date: formData.get('birth_date'),
                    id_card: formData.get('id_card') || null,
                    phone: formData.get('phone'),
                    address: formData.get('address') || null,
                    department_id: parseInt(formData.get('department_id')) || null,
                    position: formData.get('position'),
                    status: parseInt(formData.get('status')),
                    emergency_contact: formData.get('emergency_contact') || null,
                    emergency_phone: formData.get('emergency_phone') || null,
                    remark: formData.get('remark') || null,
                    photo_url: oldPhotoUrl  // 默认使用旧照片URL
                };

                // 处理照片上传
                const photoFile = formData.get('photo');
                if (photoFile && photoFile.size > 0) {
                    const photoFormData = new FormData();
                    photoFormData.append('photo', photoFile);
                    
                    // 1. 上传新照片
                    const photoResponse = await fetch('/api/employees/upload-photo', {
                        method: 'POST',
                        headers: {
                            'Authorization': `Bearer ${sessionStorage.getItem('token')}`
                        },
                        body: photoFormData
                    });
                    
                    if (photoResponse.ok) {
                        const photoData = await photoResponse.json();
                        employeeData.photo_url = photoData.url;  // 更新为新照片URL
                        
                        // 2. 如果有旧��片，先删除
                        if (oldPhotoUrl) {
                            await fetch(`/api/employees/${employeeId}/photo`, {
                                method: 'DELETE',
                                headers: {
                                    'Authorization': `Bearer ${sessionStorage.getItem('token')}`
                                }
                            });
                        }
                    }
                }

                // 3. 最后更新员工信息
                const response = await fetch(`/api/employees/${employeeId}`, {
                    method: 'PUT',
                    headers: {
                        'Authorization': `Bearer ${sessionStorage.getItem('token')}`,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(employeeData)
                });
                
                if (response.ok) {
                    alert('员工信息更新成功');
                    showEmployeeContent('list');
                } else {
                    const error = await response.json();
                    throw new Error(error.detail || '更新员工信息失败');
                }
            } catch (error) {
                console.error('更新员工信息失败:', error);
                alert(error.message || '更新员工信息失败，请稍后重试');
            }
        }

        // 删除员工
        async function deleteEmployee(employeeId) {
            if (!confirm('确定要删除该员工吗？此操作不可恢复！')) {
                return;
            }

            const token = sessionStorage.getItem('token');
            try {
                // 先获取员工信息，检查是否有照片需要删除
                const employeeResponse = await fetch(`/api/employees/${employeeId}`, {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                
                if (employeeResponse.ok) {
                    const employee = await employeeResponse.json();
                    
                    // 如果有照片，先删除照片
                    if (employee.photo_url) {
                        await fetch(`/api/employees/${employeeId}/photo`, {
                            method: 'DELETE',
                            headers: {
                                'Authorization': `Bearer ${token}`
                            }
                        });
                    }
                    
                    // 删除员工信息
                    const response = await fetch(`/api/employees/${employeeId}`, {
                        method: 'DELETE',
                        headers: {
                            'Authorization': `Bearer ${token}`
                        }
                    });
                    
                    if (response.ok) {
                        alert('员工删除成功');
                        // 刷新员工列表
                        loadEmployeeList();
                    } else {
                        const error = await response.json();
                        throw new Error(error.detail || '删除员工失败');
                    }
                }
            } catch (error) {
                console.error('删除员工失败:', error);
                alert(error.message || '删除员工失败，请稍后重试');
            }
        }

        // 处理导入员工
        async function handleImportEmployees(event) {
            event.preventDefault();
            const form = event.target;
            const formData = new FormData(form);
            const resultDiv = document.getElementById('importResult');
            
            try {
                resultDiv.innerHTML = '<div class="alert alert-info">正在导入，请稍候...</div>';
                
                const response = await fetch('/api/employees/import', {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${sessionStorage.getItem('token')}`
                    },
                    body: formData
                });
                
                if (response.ok) {
                    const result = await response.json();
                    resultDiv.innerHTML = `
                        <div class="alert alert-success">
                            <h4>导入完成</h4>
                            <p>成功导入: ${result.created} 条记录</p>
                            ${result.errors > 0 ? `
                                <p>失败: ${result.errors} 条记录</p>
                                <div class="error-details">
                                    ${result.error_details.map(error => `<div>${error}</div>`).join('')}
                                </div>
                            ` : ''}
                        </div>
                    `;
                    form.reset();
                } else {
                    const error = await response.json();
                    throw new Error(error.detail || '导入失败');
                }
            } catch (error) {
                console.error('导入失败:', error);
                resultDiv.innerHTML = `
                    <div class="alert alert-danger">
                        导入失��: ${error.message}
                    </div>
                `;
            }
        }

        // 处理导出员工
        async function handleExportEmployees() {
            try {
                // 获取筛选条件
                const name = document.getElementById('exportNameSearch').value.trim();
                const departmentId = document.getElementById('exportDepartmentSearch').value;
                const status = document.getElementById('exportStatusSearch').value;
                
                // 构建查询参数
                const params = new URLSearchParams();
                if (name) params.append('name', name);
                if (departmentId) params.append('department_id', departmentId);
                if (status) params.append('status', status);
                
                // 获取token
                const token = sessionStorage.getItem('token');
                
                // 构建导出URL
                const url = `/api/employees/export${params.toString() ? '?' + params.toString() : ''}`;
                
                // 使用fetch下载文件
                const response = await fetch(url, {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                
                if (response.ok) {
                    // 获取文件名
                    const contentDisposition = response.headers.get('content-disposition');
                    const filename = contentDisposition ? 
                        contentDisposition.split('filename=')[1].replace(/"/g, '') : 
                        'employees.xlsx';
                    
                    // 下载文件
                    const blob = await response.blob();
                    const downloadUrl = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = downloadUrl;
                    a.download = filename;
                    document.body.appendChild(a);
                    a.click();
                    window.URL.revokeObjectURL(downloadUrl);
                    a.remove();
                } else {
                    throw new Error('导出失败');
                }
            } catch (error) {
                console.error('导出失败:', error);
                alert('导出失败，请稍后重试');
            }
        }

        // 搜索要导出的员工
        async function searchExportEmployees() {
            const token = sessionStorage.getItem('token');
            const tbody = document.getElementById('exportPreviewBody');
            const countSpan = document.getElementById('exportCount');
            
            // 添加加载中提示
            tbody.innerHTML = '<tr><td colspan="7" style="text-align: center;">加载中...</td></tr>';
            
            try {
                // 获取搜索条件，使用 trim() 去除空白
                const name = document.getElementById('exportNameSearch').value.trim();
                const departmentId = document.getElementById('exportDepartmentSearch').value;
                const status = document.getElementById('exportStatusSearch').value;
                
                // 构建查询参数，只有当有值时才添加
                const params = new URLSearchParams();
                if (name) params.append('name', name);
                if (departmentId) params.append('department_id', departmentId);
                if (status) params.append('status', status);

                const response = await fetch(`/api/employees?${params}`, {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                
                if (!response.ok) {
                    throw new Error('获取员工数据失败');
                }
                
                const data = await response.json();
                const employees = Array.isArray(data) ? data : (data.items || []);
                
                // 更新预览表格
                tbody.innerHTML = employees.length ? 
                    employees.map(employee => `
                        <tr>
                            <td>
                                ${employee.photo_url ? 
                                    `<img src="${employee.photo_url}" 
                                        alt="员工照片" 
                                        style="width: 40px; height: 40px; border-radius: 50%; object-fit: cover;">` :
                                    '<div style="width: 40px; height: 40px; border-radius: 50%; background: #f0f0f0; display: flex; align-items: center; justify-content: center;">无</div>'
                                }
                            </td>
                            <td>${employee.name || '-'}</td>
                            <td>${employee.department_name || '-'}</td>
                            <td>${employee.position || '-'}</td>
                            <td>${employee.phone || '-'}</td>
                            <td>
                                <span class="status-badge ${getStatusClass(employee.status)}">
                                    ${getStatusText(employee.status)}
                                </span>
                            </td>
                            <td>${formatDate(employee.create_time)}</td>
                        </tr>
                    `).join('') :
                    '<tr><td colspan="7" style="text-align: center;">暂无数据</td></tr>';
                
                // 更新计数
                countSpan.textContent = `共找到 ${employees.length} 条记录`;
                
            } catch (error) {
                console.error('搜索员工失败:', error);
                tbody.innerHTML = '<tr><td colspan="7" style="text-align: center; color: #f5222d;">加载失败，请刷新重试</td></tr>';
                alert('搜索员工失败，请稍后重试');
            }
        }

        // 显示角色管理相关内容
        function showRoleContent(type, event) {
            // 更新导航项状态
            document.querySelectorAll('.nav-item').forEach(item => {
                item.classList.remove('active');
            });
            if (event && event.currentTarget) {
                event.currentTarget.classList.add('active');
            }

            const content = document.getElementById('apiContent');
            
            switch(type) {
                case 'create':
                    content.innerHTML = `
                        <div class="content-section">
                            <h2>创建角色</h2>
                            <div class="form-container">
                                <form id="createRoleForm" onsubmit="return handleCreateRole(event)">
                                    <div class="form-group">
                                        <label for="name">角色名称</label>
                                        <input type="text" id="name" name="name" required>
                                    </div>
                                    <div class="form-group">
                                        <label for="description">描述</label>
                                        <textarea id="description" name="description" rows="3"></textarea>
                                    </div>
                                    <div class="form-group">
                                        <label for="status">状态</label>
                                        <select id="status" name="status">
                                            <option value="1">启用</option>
                                            <option value="0">禁用</option>
                                        </select>
                                    </div>
                                    <button type="submit" class="btn">创建角色</button>
                                </form>
                            </div>
                        </div>
                    `;
                    break;
                    
                case 'list':
                    content.innerHTML = `
                        <div class="content-section">
                            <h2>角色列表</h2>
                            <div class="table-container">
                                <table class="data-table">
                                    <thead>
                                        <tr>
                                            <th>ID</th>
                                            <th>角色名称</th>
                                            <th>描述</th>
                                            <th>状态</th>
                                            <th>用户数量</th>
                                            <th>创建时间</th>
                                            <th>操作</th>
                                        </tr>
                                    </thead>
                                    <tbody id="roleTableBody">
                                        <!-- 角色数据将动态加载 -->
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    `;
                    loadRoleList();
                    break;
            }
        }

        // 加载角色列表
        async function loadRoleList() {
            const token = sessionStorage.getItem('token');
            try {
                const response = await fetch('/api/roles', {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                
                if (response.ok) {
                    const roles = await response.json();
                    const tbody = document.getElementById('roleTableBody');
                    tbody.innerHTML = roles.map(role => `
                        <tr>
                            <td>${role.id}</td>
                            <td>${role.name}</td>
                            <td>${role.description || '-'}</td>
                            <td>
                                <span class="status-badge ${role.status === 1 ? 'status-active' : 'status-inactive'}">
                                    ${role.status === 1 ? '启用' : '禁用'}
                                </span>
                            </td>
                            <td>${role.user_count || 0}</td>
                            <td>${formatDate(role.create_time)}</td>
                            <td>
                                <button onclick="editRole(${role.id})" class="btn-small">编辑</button>
                                <button onclick="deleteRole(${role.id})" class="btn-small btn-danger">删除</button>
                            </td>
                        </tr>
                    `).join('');
                }
            } catch (error) {
                console.error('加载角色列表失败:', error);
                alert('加载角色列表失败，请稍后重试');
            }
        }

        // 处理创建角色
        async function handleCreateRole(event) {
            event.preventDefault();
            const form = event.target;
            const formData = new FormData(form);
            
            try {
                const response = await fetch('/api/roles', {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${sessionStorage.getItem('token')}`,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        name: formData.get('name'),
                        description: formData.get('description') || null,
                        status: parseInt(formData.get('status'))
                    })
                });
                
                if (response.ok) {
                    alert('角色创建成功');
                    showRoleContent('list');
                } else {
                    const error = await response.json();
                    throw new Error(error.detail || '创建角色失败');
                }
            } catch (error) {
                console.error('创建角色失败:', error);
                alert(error.message || '创建角色失败，请稍后重试');
=======
                    const employees = await response.json();
                    const select = document.getElementById('manager');
                    select.innerHTML = '<option value="">暂不设置</option>' +
                        employees.map(emp => `
                            <option value="${emp.id}">${emp.name}</option>
                        `).join('');
                }
            } catch (error) {
                console.error('加载员工选项失败:', error);
>>>>>>> 3c947f1aba3ee54d50472e0f837782629d528bae
            }
        }
    </script>
</body>
</html> 